结合字符串

时间:2011-12-03 21:12:20

标签: python

假设我有两个字符串列表,我想通过组合两个列表来创建一个新列表,这样第一个列表中的第一个字符串将位于第二个列表中第一个字的元组中,第二个第二个等等...

仅举例:

input: lst1 = ["hello", "first", "is"]
input: lst2 = ["my", "name", "tom"]
output: [("hello","my"), ("first", "name"), ("is", "tom")]
我写了类似的东西:

lst1 = ["hello", "first", "is"]
lst2 = ["my", "name", "tom"]
new_list = []
    for i in lst1 :
            for j in lst2 :
                    two_words = (i, j)
                    new_list.append(two_words)
    return new_list

我在这里做错了什么?

4 个答案:

答案 0 :(得分:6)

zip正在寻找:

>>> lst1 = ["hello", "first", "is"]
>>> lst2 = ["my", "name", "tom"]
>>> zip(lst1,lst2)
[('hello', 'my'), ('first', 'name'), ('is', 'tom')]

有关它的更多信息:http://docs.python.org/library/functions.html#zip

答案 1 :(得分:4)

Julio的回答实际上是做到这一点的pythonic方式。但至于你的问题,你做错了什么,你的错误就在这里:

    for i in lst1 :
            for j in lst2 :

您不希望迭代这样的列表,因为您只希望结果与两个列表的大小相同。假设两个列表的大小相同,则只需

lst1 = ["hello", "first", "is"]
lst2 = ["my", "name", "tom"]
new_list = []
    for i in range(len(lst1)):
                    new_list.append((lst1[i], list2[i]))
    return new_list

答案 2 :(得分:1)

你的问题是循环中的循环形成了“交叉产品”,从两个列表中创建了每对可能的字符串。解决方案是使用zip,或者对可能的索引进行单循环。

答案 3 :(得分:0)

使用列表推导来实现它的最佳和最简单的方法。

lst1 = ["hello", "first", "is"]
lst2 = ["my", "name", "tom"]
new_list = [ ( lst1[i], lst2[i] ) for i in range ( len(lst1) ) ]

如果你想让内部元素在列表中, 使用

new_list = [ [ lst1[i], lst2[i] ] for i in range ( len(lst1) ) ]

输出:

[('hello', 'my'), ('first', 'name'), ('is', 'tom')]
相关问题