繁体   English   中英

Python列表附加相应的索引

[英]Python List append with respective index

我需要列表附加上的帮助。 我必须将其与相应的列表索引一起导出为CSV。

lst1 = ['a', 'b', 'c']
lst2 = ['w', 'f', 'g']
lst3 = ['e', 'r', 't']

ap = []

ap.append((lst1, lst2, lst3))

output: [(['a', 'b', 'c'], ['w', 'f', 'g'], ['e', 'r', 't'])]

预期产量:

[('a', 'w', 'e')
 ('b', 'f', 'r')
 ('c', 'g', 't')]

我需要通过Pandas导出到Excel,请帮忙。

 col1   col2    col3
 a       w       e
 b       f       r
 c       g       t

您需要一个元组列表,而不是一个列表元组列表。 为了获得更好的结果,您可以将zip与解zip结合使用,以按索引提取可迭代列表中的项目。

df = pd.DataFrame(list(zip(*(lst1, lst2, lst3))),
                  columns=['col1', 'col2', 'col3'])

print(df)

  col1 col2 col3
0    a    w    e
1    b    f    r
2    c    g    t

然后像往常一样导出到Excel:

df.to_excel('file.xlsx', index=False)

暂无
暂无

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

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