python - 使用列表理解映射列表中的项目?

标签 python list python-3.x loops

我对循环内的列表理解有疑问。我想将一个列表中的项目添加到另一个列表。

我在列表理解中使用 map classzip

from pandas import Series, DataFrame
import pandas
x = ['a', 'b', 'c', 'd', 'e']
y = [2, 3, 6, 7, 4]
ser = {'A': Series(x), 'B': Series(y)}
df = DataFrame(ser)
targets = df['A'].tolist()
df['A1999'] = [i + 1 for i in df['B']]
df['A2000'] = [i + 2 for i in df['B']]
df['A2001'] = [i + 3 for i in df['B']]
df['A2002'] = [i + 1.7 for i in df['B']]
df['A2003'] = [i + 1.1 for i in df['B']]
y = range(1999, 2004)
gaps = []
for t in targets:
    temp = []
    years = []
    for ele in y:
        target = 'A' + str(ele)
        new = df[target][df['A'] == t].tolist()
        temp.append(new)
        years.append(ele)
        gap = [list(map(list, zip(years, item))) for item in temp]
    gaps.append(gap)

输出:

[[[[1999, 3]], [[1999, 4]], [[1999, 5]], [[1999, 3.7000000000000002]],
  [[1999, 3.1000000000000001]]]...

我要找的是:

[[[[1999, 3]], [[2000, 4]], [[2001, 5]], [[2002, 3.7000000000000002]],
  [[2003, 3.1000000000000001]]]...

我怎样才能修复列表理解,以便添加 years list 中的所有年份,而不仅仅是第一个(即 1999 年)

我试过这个例子,但我想我在做同样的事情:

gap = [[[years[i], x] for i, x in enumerate(y)] for y in temp]

gap = [list(map(list, zip([[y] for y in years], item))) for item in temp]

最佳答案

用这个替换 gap =

[list((x,y[0])) for x,y in zip(years,temp)]

关于python - 使用列表理解映射列表中的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39455561/

相关文章:

python - Centos 上带有 sqlite3 模块的 python 2.7.3 的问题

c# - stri_replace_all_fixed 相当于 : Replace values based on list

python - C 字符串中的十六进制小数

python - 删除两个列表中的公共(public)元素

python - 如何检查 float 字符串?

python - 如果列表中的列存在于 Python Pandas 的 DataFrame 中,如何将 DataFrame 中除列表中的列之外的所有列置于上方?

php - 如何从数组键 => 值中创建一个没有键的简单数组?

python - 检查字符串输入是否正确

python - 使用 PIL 调整大小时丢失图像格式

python - 使用行列表,无论我有 1 行还是 N 行