我在循环中遇到列表推导问题。我想将一个列表中的项目添加到另一个列表中。
我在列表理解中使用ui
和map class
。
zip
输出:
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]]]...
的所有年份,而不仅仅是第一个(即1999年)
我尝试了这个例子,但我认为我做的是同样的事情:
years list
或
gap = [[[years[i], x] for i, x in enumerate(y)] for y in temp]
答案 0 :(得分:2)
用此
替换gap =[list((x,y[0])) for x,y in zip(years,temp)]