Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用列表理解从列表映射项目?_Python_List_Python 3.x_Loops - Fatal编程技术网

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

Python 使用列表理解从列表映射项目?,python,list,python-3.x,loops,Python,List,Python 3.x,Loops,我对循环中的列表理解有问题。我想将项目从一个列表添加到另一个列表 我正在列表中使用map类和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'] =

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

我正在列表中使用
map类
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年)

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

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


将gap=替换为此

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

在第二个循环中,为y中的元素
分配了很多值,但只添加了最后一个值(因为
间隙。append(间隙)
在循环之外。应该是这样吗?例如,这个项目
[[2000,4]]
是你真正需要的吗(与
[2000,4]
相反)?是的。
间隙。append(间隙)
必须在外面,否则所有的
gap
将是年
lenght
,我想要的是目标
lenght
@CristiFati实际上你是对的。
[2000,4]
应该是正确的输出。为了
附加
gap
的结果,我使用了一个空列表
gaps=[]
这就是输出不同的原因:我们的示例代码没有运行
[list((x,y[0])) for x,y in zip(years,temp)]