简体   繁体   English

按行合并列表 (Python)

[英]Combine lists row-wise (Python)

Let's say I have 3 different lists假设我有 3 个不同的列表

col1 = ['2006-03-28','2006-04-05','2006-04-06']
col2 = ['IBM', 'MSFT', 'IBM']
col3 = [1000, 1000, 500]

What is the most efficient way to combine those lists in another list like this:将这些列表组合到另一个列表中的最有效方法是什么:

col = [('2006-03-28', 'IBM', 1000),
       ('2006-04-05', 'MSFT', 1000),
       ('2006-04-06', 'IBM', 500)]
>>> col1 = ['2006-03-28','2006-04-05','2006-04-06']
>>> col2 = ['IBM', 'MSFT', 'IBM']
>>> col3 = [1000, 1000, 500]
>>> list(zip(col1, col2, col3))
[('2006-03-28', 'IBM', 1000), ('2006-04-05', 'MSFT', 1000), ('2006-04-06', 'IBM', 500)]

If your columns are already in one list you can just use zip(*cols)如果您的列已经在一个列表中,您可以使用zip(*cols)

The code is as follows: Python 3.x代码如下:Python 3.x

>>> col1 = ['2006-03-28','2006-04-05','2006-04-06']
>>> col2 = ['IBM', 'MSFT', 'IBM']
>>> col3 = [1000, 1000, 500]

>>> col = list(zip(col1 ,col2 ,col3 ))

>>> print(str(col))

[('2006-03-28', 'IBM', 1000),
 ('2006-04-05', 'MSFT', 1000),
 ('2006-04-06', 'IBM', 500)]

Just the zip() syntax by it self works for Python 2.x.仅 zip() 语法本身适用于 Python 2.x。 Use the above code to combine lists as row wise (or as spread sheet columns) in Python 3.x.使用上面的代码在 Python 3.x 中以行方式(或作为电子表格列)组合列表。

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

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