如何在两个" array.flatten()" -ed列表中创建python中的字符串列表

时间:2016-07-14 16:36:44

标签: python arrays string list

我希望在python中创建以下列表:

list = ["pix420_615", "pix421_615", ... , "pix425_620"]

N.B。列表是字符串列表,而不是值。

来自以下两个列表:

x= [420, 421, 422, 423, 424, 425, 420, 421, 422, 423, 424, 425, 420, 421, 422, 423, 424, 425,
 420, 421, 422, 423, 424, 425, 420, 421, 422, 423, 424, 425, 420, 421, 422, 423, 424, 425]

y= [615, 615, 615, 615, 615, 615, 616, 616, 616, 616, 616, 616, 617, 617, 617, 617, 617, 617,
 618, 618, 618, 618, 618, 618, 619, 619, 619, 619, 619, 619, 620, 620, 620, 620, 620, 620]

我想知道如何做到这一点,并保持相应数组值的一致性......?

3 个答案:

答案 0 :(得分:2)

这应该可以解决问题。 zip是做这种事情的最好方法:

x = [420, 421, 422, 423, 424, 425, 420, 421, 422, 423, 424, 425, 420, 421, 422, 423, 424, 425, 420, 421, 422, 423, 424, 425, 420, 421, 422, 423, 424, 425, 420, 421, 422, 423, 424, 425]

y = [615, 615, 615, 615, 615, 615, 616, 616, 616, 616, 616, 616, 617, 617, 617, 617, 617, 617, 618, 618, 618, 618, 618, 618, 619, 619, 619, 619, 619, 619, 620, 620, 620, 620, 620, 620]

z = ['pix{}_{}'.format(a, b) for a, b in zip(x, y)]

print(z)

# Output:
# ['pix420_615', 'pix421_615', 'pix422_615', 'pix423_615', 'pix424_615', 'pix425_615', 'pix420_616', 'pix421_616', 'pix422_616', 'pix423_616', 'pix424_616', 'pix425_616', 'pix420_617', 'pix421_617', 'pix422_617', 'pix423_617', 'pix424_617', 'pix425_617', 'pix420_618', 'pix421_618', 'pix422_618', 'pix423_618', 'pix424_618', 'pix425_618', 'pix420_619', 'pix421_619', 'pix422_619', 'pix423_619', 'pix424_619', 'pix425_619', 'pix420_620', 'pix421_620', 'pix422_620', 'pix423_620', 'pix424_620', 'pix425_620']

答案 1 :(得分:2)

从您的列表中

map(lambda t: 'pix%s_%s' % t, zip(x, y))

['pix%s_%s' % t for t in zip(x, y)]

但是,我注意到第一个列表基本上是[420, ..., 425],第二个列表是[615, ...],这导致zip(x, y)表示range(420, 426)和{{range(620, 626)的乘积1}}。

您可以通过以下方式简化所有这些:

from itertools import product

['pix%s_%s' % (y, x) for x, y in product(range(615, 621), range(420, 426))]

答案 2 :(得分:0)

使用map功能

map(lambda a, b: 'pix{0}_{1}'.format(a,b), x, y)