我想将字符串与给定字符串列表中的每个元素连接起来:
my_variable = 'Blue'
my_list = ['House', 'Paint', 'Cloth']
如何将my_variable连接到my_list中的每个元素,以便我有一个新列表
my_new_list = ['Blue_House', 'Blue_Paint', 'Blue_Cloth']
答案 0 :(得分:2)
或使用列表理解:
print([my_variable + '_' + e for e in my_list])
['Blue_House', 'Blue_Paint', 'Blue_Cloth']
答案 1 :(得分:1)
["_".join([my_variable, i]) for i in my_list]
# ['Blue_House', 'Blue_Paint', 'Blue_Cloth']
答案 2 :(得分:0)
创建一个新列表并遍历原始列表,将原始列表的条目附加到新列表中,并将“Blue_”添加到前面,带有一个简单的+
my_variable = 'Blue'
my_list = ['House', 'Paint', 'Cloth']
new_list = []
for entry in my_list:
new_list.append(my_variable + "_" + str(entry))
print new_list
>>>>['Blue_House', 'Blue_Paint', 'Blue_Cloth']
答案 3 :(得分:-1)
my_variable1 = 'Blue'
my_variable2 = 'Red'
my_variable3 = 'Black'
my_list = ['House', 'Paint', 'Cloth']
def mergetwo(a, b, s):
return s.join((a,b))
def prefix(item, pre):
return lambda sep: mergetwo(pre,item,sep)
def suffix(item, suf):
return prefix(suf, item)
def mergewith(alist):
return lambda position: lambda sep: lambda var: list(map(lambda item: position(item, var)(sep), alist))
def addprefix_underscore_mylist(var):
return mergewith(my_list)(prefix)('_')(var)
def addsuffix_underscore_mylist(var):
return mergewith(my_list)(suffix)('_')(var)
print(addprefix_underscore_mylist(my_variable1))
print(addprefix_underscore_mylist(my_variable2))
print(addprefix_underscore_mylist(my_variable3))
print(addsuffix_underscore_mylist(my_variable1))
print(addsuffix_underscore_mylist(my_variable2))
print(addsuffix_underscore_mylist(my_variable3))