在Python中明智地串联两个Strings元素列表,而没有嵌套的for循环 [英] Concatenating two lists of Strings element wise in Python without Nested for loops
问题描述
我有两个字符串列表: ls1 = ['a','b','c','d']
和 ls2 = ['k','j','l','m']
I have two lists of strings:
ls1 = ['a','b','c','d']
and ls2 = ['k','j','l','m']
我想创建第三个列表: ls3 = ['a-k','a-j','a-l','a-m','b-k','b-j','b-l','b-m'...'d-m']
,其中包含16个元素.
I want to create a 3rd list: ls3 = ['a-k','a-j','a-l','a-m','b-k','b-j','b-l','b-m'...'d-m']
which has 16 elements.
我可以使用以下嵌套的 for
循环
I can achieve this quite easily with the following nested for
loops
ls3 = []
for elem in ls1:
for item in ls2:
ls3.append(elem+'-'+item)
但是,这不是Python风格,它揭示了我的C代码背景.
However, this isn't very Pythonic and reveals my C-code background.
我尝试了使用 map
和 lambda
的更加Pythonic的解决方案:
I attempted a more Pythonic solution with map
and lambda
:
[ map(lambda x,y: x+'-'+y, a,b) for a,b in zip(ls1,ls2) ]
但是我真的不知道我在做什么.
But I don't really know what I'm doing yet.
通过嵌套的 for
循环可以完成我的工作的Python方法是什么?
What is a Pythonic way to achieve what I've done with my nested for
loops?
推荐答案
您所使用的技术完全是Python风格的,并且在将列表理解引入语言之前,它还是属于规范的.但是,您建议使用 zip
的那个将不起作用,因为您希望使用 ls1
和 ls2
中的所有成对元素,但要使用> zip
只是使用相应的元素而不是所有组合来创建对.
The technique you have used is perfectly Pythonic, and until list comprehensions were introduced into the language would have been canonical. The one you suggest using zip
, however, won't work, because you want all pairs of elements from ls1
and ls2
, but zip
simply creates pairs using the corresponding elements rather than all combinations.
如果您想使用更紧凑的代码,则应该使用适当的列表理解
If you'd like to use more compact code then the appropriate list comprehension would be
ls3 = [x+'-'+y for x in ls1 for y in ls2]
对于大型列表,或者在需要每盎司性能的情况下(这永远不是您的首要考虑),请参阅@PaulPanzer的答案,他解释了一种更高效但稍微复杂的技术.
For large lists, or where you need every ounce of performance (which should never be your first consideration) see the answer from @PaulPanzer, who explains a more efficient though slightly more complex technique.
这篇关于在Python中明智地串联两个Strings元素列表,而没有嵌套的for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!