简体   繁体   English

将两个整数列表组合成一个字符串列表

[英]Combining two lists of ints, into one list of strings

Edit: I've realized my error (if statement, variable x is assigned to element in string and i'm comparing to length of list).. Trying to resolve that tomorrow morning. 编辑:我已经意识到我的错误(如果声明,变量x被分配给字符串中的元素,我正在与列表的长度进行比较)。试图明天早上解决这个问题。 Appologies for the stupid error but i would appreciate any bits of learning. 对于愚蠢的错误的应用,但我会感激任何学习。

I'm trying to combine two lists into a single list. 我正在尝试将两个列表组合到一个列表中。

 m = [1,2,3]
 n = [4,5,6]
 v = m+n

 def myFun():
   return [(str(x)+str(y)) for x in m if x < len(m) for y in n if y < len(n)]

 print(myFun())

the result of myFun() should display "14, 25, 36" myFun()的结果应该显示“14,25,36”

i also tried to breakdown the code into a more pythonic world and have seen where i've gone astray: 我还尝试将代码细分为一个更加pythonic的世界,并看到我误入歧途的地方:

 def my(fun()):
   for x in m if x < len(m):
     for y in n if y < len(n): # problem here, running until count 9 instead of 3
                               # like it's supposed to.. author error.. 
       newlist.append(str(x)+str(y))
   print(newlist)

Am i even headed in the right direction or should i be trying to build a map, i've seen a few pages saying that maps could be counter-productive if you have to reverse with a list-comp or lambda? 我甚至朝着正确的方向前进,或者我是否应该尝试构建一张地图,我已经看过几页说如果你不得不用list-comp或lambda反转地图可能会适得其反? Also, is it possible to count a specific object inside a list comprehension / lambda? 此外,是否可以计算列表理解/ lambda中的特定对象? (eg list length)? (例如列表长度)?

use zip() : 使用zip()

In [8]: m = [1,2,3]

In [9]: n = [4,5,6]

In [10]: [str(x)+str(y) for x,y in zip(m,n)]
Out[10]: ['14', '25', '36']

or use itertools.izip_longest() if the lists are of different lengths: 或者如果列表长度不同,则使用itertools.izip_longest()

In [2]: m=[1,2,3]

In [3]: n=[4,5,6,7]

In [4]: from itertools import izip_longest

In [5]: [str(x)+str(y) for x,y in izip_longest(m,n,fillvalue="")]
Out[5]: ['14', '25', '36', '7']

使用地图:

map(lambda a, b: str(a) + str(b), m, n)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM