假设我有两个字符串列表,我想通过组合两个列表来创建一个新列表,这样第一个列表中的第一个字符串将位于第二个列表中第一个字的元组中,第二个列表中的第二个字符串等......
仅举例如:
input: lst1 = ["hello", "first", "is"]
input: lst2 = ["my", "name", "tom"]
output: [("hello","my"), ("first", "name"), ("is", "tom")]
Run Code Online (Sandbox Code Playgroud)
我写了类似的东西:
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
Run Code Online (Sandbox Code Playgroud)
我在这做错了什么?
zip 正是你要找的:
>>> lst1 = ["hello", "first", "is"]
>>> lst2 = ["my", "name", "tom"]
>>> zip(lst1,lst2)
[('hello', 'my'), ('first', 'name'), ('is', 'tom')]
Run Code Online (Sandbox Code Playgroud)
更多关于它:http://docs.python.org/library/functions.html#zip
| 归档时间: |
|
| 查看次数: |
686 次 |
| 最近记录: |