【问题标题】:How to merge two lists into a sequence of columns in python? [duplicate]如何将两个列表合并为python中的列序列? [复制]
【发布时间】:2014-03-08 05:32:15
【问题描述】:

假设我有两个列表:

t1 = ["abc","def","ghi"]  
t2 = [1,2,3]

如何使用 python 合并它,以便输出列表为:

t =  [("abc",1),("def",2),("ghi",3)]

我试过的程序是:

t1 = ["abc","def"]  
t2 = [1,2]         
t = [ ]  
for a in t1:  
        for b in t2:  
                t.append((a,b))  
print t

输出是:

[('abc', 1), ('abc', 2), ('def', 1), ('def', 2)]

我不想重复输入。

【问题讨论】:

  • [...] 是一个列表,(...) 是一个元组。
  • 抱歉,Christian,感谢您的指正

标签: python


【解决方案1】:

在 Python 2.x 中,您可以只使用zip

>>> t1 = ["abc","def","ghi"]
>>> t2 = [1,2,3]
>>> zip(t1, t2)
[('abc', 1), ('def', 2), ('ghi', 3)]
>>>

但是,在 Python 3.x 中,zip 返回一个 zip 对象(这是一个 iterator)而不是一个列表。这意味着您必须将结果显式转换为列表,将它们放入list

>>> t1 = ["abc","def","ghi"]
>>> t2 = [1,2,3]
>>> zip(t1, t2)
<zip object at 0x020C7DF0>
>>> list(zip(t1, t2))
[('abc', 1), ('def', 2), ('ghi', 3)]
>>>

【讨论】:

  • 可能是错的,但我认为您第一次阅读时是正确的。我认为压缩列表是 OP 想要的,你写的是 OP 的尝试所产生的,但是 OP“[不]想要重复的条目”。
  • @DSM - 就是这样。我需要再来一杯咖啡……
【解决方案2】:

使用邮编:

>>> t1 = ["abc","def","ghi"]
>>> t2 = [1,2,3]
>>> list(zip(t1,t2))
[('abc', 1), ('def', 2), ('ghi', 3)]
# Python 2 you do not need 'list' around 'zip' 

如果你不想重复的项目,并且你不关心顺序,使用一个集合:

>>> l1 = ["abc","def","ghi","abc","def","ghi"]
>>> l2 = [1,2,3,1,2,3]
>>> set(zip(l1,l2))
set([('def', 2), ('abc', 1), ('ghi', 3)])

如果你想按顺序唯一化:

>>> seen=set()
>>> [(x, y) for x,y in zip(l1,l2) if x not in seen and (seen.add(x) or True)]
[('abc', 1), ('def', 2), ('ghi', 3)]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多