[英]Combine each element in a list of strings with another string
my input is: 我的输入是:
list1=['car','bike','mango']
and I want to append "JNU" to every item. 我想在每个项目后面附加“ JNU”。 Desired output: 所需的输出:
list1=[('car', 'JNU'), ('bike', 'JNU'), ('mango', 'JNU')]
I'm unable to get that result. 我无法得到那个结果。
In [13]: list1 = ['car', 'bike', 'mango']
In [14]: list1 = [(el, 'JNU') for el in list1]
In [15]: list1
Out[15]: [('car', 'JNU'), ('bike', 'JNU'), ('mango', 'JNU')]
You could use zip()
and itertools.repeat()
: 您可以使用zip()
和itertools.repeat()
:
import itertools
list1 = zip(list1, itertools.repeat('JNU'))
Demo: 演示:
>>> import itertools
>>> list1 = ['car','bike','mango']
>>> zip(list1, itertools.repeat('JNU'))
[('car', 'JNU'), ('bike', 'JNU'), ('mango', 'JNU')]
Another variation... 另一种变化
list1 = ['car', 'bike', 'mango']
from itertools import product
list2 = list(product(list1, ['JNU']))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.