简体   繁体   English

使用列表理解从列表中映射项目?

[英]map items from list using list comprehension?

I have a problem with a list comprehension inside a loop. 我在循环中遇到列表推导问题。 I want to add items from one list to an other. 我想将一个列表中的项目添加到另一个列表中。

I'm using map class and zip inside the list comprehension. 我在列表理解中使用了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)

And the output: 并输出:

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

What I'm looking for is: 我正在寻找的是:

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

How can I fix the list comprehension in order to add all years from years list and not only the first (ie 1999) 如何修复列表理解以便从years list添加所有年份,而不仅仅是第一个(即1999年)

I tried with this example, but I think I'm doing the same thing: 我试过这个例子,但我想我做的是同样的事情:

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

or 要么

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

用这个替换间隙=

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM