简体   繁体   English

将字符串列表中的每个元素与另一个字符串合并

[英]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.

相关问题 如何将字符串连接到字符串列表的每个元素? - How to concatenate a string to each element of a list of strings? 如果字符串是同一列表中另一个较大字符串的一部分,则合并它们 - Combine strings if they are part of another larger string in the same list 修改Python列表的每个元素,并将结果组合成字符串 - Modify each element of a Python list and combine results into a string 创建一个列表,其中每个 list[j] 是另一个字符串列表中每个元素的字符 j - Creating a list where each list[j] is the character j from each element in another list of strings 将一个列表的每个字符串元素连接到另一个列表的所有元素 - Concatenate each string element of one list to all elements of another list 如何将列表的字符串合并为一个元素? - How to combine strings of a list into one element? 如果第一个字符与列表中的另一个字符串元素匹配,则删除字符串列表中的字符串元素 - Remove string element in a list of strings if the first characters match with another string element in the list 根据另一个字符串列表(例如黑名单字符串)从字符串列表中每个元素的末尾删除字符 - Remove characters from the end of each element in a list of strings based on another list of strings (e.g. blacklist strings) Python如何结合列表的每个元素 - Python How combine each element of a list 将一个列表的字符串元素附加到 python 中每个子列表中另一个列表的 integer 元素 - attach the string element of one list to the integer element of another subsist of a list in each sub list in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM