组合字符串
假设我有 2 个字符串列表,我想通过组合这两个列表来创建一个新列表,以便第一个列表中的第一个字符串将与第二个列表中的第一个单词位于一个元组中,第二个与第二个单词位于一个元组中等等...
举个例子:
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
我在这里做错了什么?
Let's say I have 2 lists of strings, and I want to make a new list by combining the two lists so that the first string in the first list, will be in a tuple with the first word in the second list, second with second and so on...
Just for example:
input: lst1 = ["hello", "first", "is"]
input: lst2 = ["my", "name", "tom"]
output: [("hello","my"), ("first", "name"), ("is", "tom")]
I wrote something like that:
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
What am I doing wrong here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用列表推导式是最好、最简单的方法。
如果您希望内部元素位于列表中,
使用
输出:
The best and simplest way to do it using list comprehensions.
if you want the inner elements to be in a list,
use
output:
zip
是您要查找的内容:更多信息:http ://docs.python.org/library/functions.html#zip
zip
is what you're looking for:More about it: http://docs.python.org/library/functions.html#zip
Julio 的答案实际上是Pythonic 的做法。但至于你的问题你做错了什么,你的错误就在这里:
你不想像这样迭代列表,因为你只想要一个与两个列表大小相同的结果。假设两个列表的大小相同,那就简单了
Julio's answer is in fact the pythonic way of doing it. But as to your question what you're doing wrong, your error is here:
You don't want to iterate over the lists like that, because you only want a result that is the same size as both lists. Assuming both lists are the same size, it would simply be
您的问题是循环内的循环形成“叉积”,从两个列表创建每个可能的字符串对。解决方案是使用
zip
,或者对可能的索引进行单个循环。Your problem is that a loop inside a loop forms a "cross product", creating every possible pair of strings from the two lists. The solution is to use
zip
, or to make a single loop over the possible indices.