将相同的字符串附加到 Python 中的字符串列表
- 2025-01-21 09:01:00
- admin 原创
- 77
问题描述:
我尝试取一个字符串,并将其附加到列表包含的每个字符串,然后得到一个包含完整字符串的新列表。示例:
list1 = ['foo', 'fob', 'faz', 'funk']
string = 'bar'
*magic*
list2 = ['foobar', 'fobbar', 'fazbar', 'funkbar']
我尝试了 for 循环,并尝试了列表理解,但结果很糟糕。一如既往,任何帮助,我都非常感谢。
解决方案 1:
最简单的方式是使用列表推导:
[s + mystring for s in mylist]
请注意,我避免使用内置名称,list
因为这会遮蔽或隐藏内置名称,这非常不好。
另外,如果您实际上不需要列表,而只需要迭代器,则生成器表达式会更高效(尽管它在短列表上可能并不重要):
(s + mystring for s in mylist)
它们非常强大、灵活且简洁。每个优秀的 Python 程序员都应该学会使用它们。
解决方案 2:
my_list = ['foo', 'fob', 'faz', 'funk']
string = 'bar'
my_new_list = [x + string for x in my_list]
print my_new_list
这将打印:
['foobar', 'fobbar', 'fazbar', 'funkbar']
解决方案 3:
map
对我来说这似乎是适合这个工作的工具。
my_list = ['foo', 'fob', 'faz', 'funk']
string = 'bar'
list2 = list(map(lambda orig_string: orig_string + string, my_list))
请参阅有关函数式编程工具的部分以获取更多示例map
。
解决方案 4:
这是一个使用 的简单答案pandas
。
import pandas as pd
list1 = ['foo', 'fob', 'faz', 'funk']
string = 'bar'
list2 = (pd.Series(list1) + string).tolist()
list2
# ['foobar', 'fobbar', 'fazbar', 'funkbar']
解决方案 5:
更新更多选项
以下是我遵循的一些方法,我相信还会有更多。
方法 1:
list1 = ['foo', 'fob', 'faz', 'funk']
list2 = [ls+"bar" for ls in list1] # using list comprehension
print(list2)
方法 2:
list1 = ['foo', 'fob', 'faz', 'funk']
list2 = list(map(lambda ls: ls+"bar", list1))
print(list2)
方法 3:
list1 = ['foo', 'fob', 'faz', 'funk']
addstring = 'bar'
for index, value in enumerate(list1):
list1[index] = addstring + value #this will prepend the string
#list1[index] = value + addstring #this will append the string
方法 4:
list1 = ['foo', 'fob', 'faz', 'funk']
addstring = 'bar'
list2 = []
for value in list1:
list2.append(str(value) + "bar")
print(list2)
方法 5:
list1 = ['foo', 'fob', 'faz', 'funk']
list2 = list(map(''.join, zip(list1, ["bar"]*len(list1))))
print(list2)
避免使用关键字作为变量,如“list”,而应将“list”重命名为“list1”
解决方案 6:
以 Python 方式运行以下实验:
[s + mystring for s in mylist]
似乎比明显使用这样的 for 循环快 ~35%:
i = 0
for s in mylist:
mylist[i] = s+mystring
i = i + 1
实验
import random
import string
import time
mystring = '/test/'
l = []
ref_list = []
for i in xrange( 10**6 ):
ref_list.append( ''.join(random.choice(string.ascii_lowercase) for i in range(10)) )
for numOfElements in [5, 10, 15 ]:
l = ref_list*numOfElements
print 'Number of elements:', len(l)
l1 = list( l )
l2 = list( l )
# Method A
start_time = time.time()
l2 = [s + mystring for s in l2]
stop_time = time.time()
dt1 = stop_time - start_time
del l2
#~ print "Method A: %s seconds" % (dt1)
# Method B
start_time = time.time()
i = 0
for s in l1:
l1[i] = s+mystring
i = i + 1
stop_time = time.time()
dt0 = stop_time - start_time
del l1
del l
#~ print "Method B: %s seconds" % (dt0)
print 'Method A is %.1f%% faster than Method B' % ((1 - dt1/dt0)*100)
结果
Number of elements: 5000000
Method A is 38.4% faster than Method B
Number of elements: 10000000
Method A is 33.8% faster than Method B
Number of elements: 15000000
Method A is 35.5% faster than Method B
解决方案 7:
结合map
和format
:
>>> list(map('{}bar'.format, ['foo', 'fob', 'faz', 'funk']))
['foobar', 'fobbar', 'fazbar', 'funkbar']
因此,没有循环变量。
它适用于 Python 2 和 3。(在 Python 3 中可以写[*map(...)]
,而在 Python 2 中只需map(...)
。
如果喜欢模表达式
>>> list(map('%sbar'.__mod__, ['foo', 'fob', 'faz', 'funk']))
['foobar', 'fobbar', 'fazbar', 'funkbar']
可以使用__add__
方法
>>> list(map('bar'.__add__, ['foo', 'fob', 'faz', 'funk']))
['barfoo', 'barfob', 'barfaz', 'barfunk']
解决方案 8:
从 Python 3.6 开始,使用 f 字符串是最佳实践(而不是format
或 连接+
)。请参阅PEP498。
list1 = ['foo', 'fob', 'faz', 'funk']
mystring = 'bar'
list2 = [f"{s}{mystring}" for s in list1]
解决方案 9:
稍微扩展一下“将字符串列表附加到字符串列表”:
import numpy as np
lst1 = ['a','b','c','d','e']
lst2 = ['1','2','3','4','5']
at = np.full(fill_value='@',shape=len(lst1),dtype=object) #optional third list
result = np.array(lst1,dtype=object)+at+np.array(lst2,dtype=object)
结果:
array(['a@1', 'b@2', 'c@3', 'd@4', 'e@5'], dtype=object)
dtype odject 可以进一步转换为 str
解决方案 10:
new_list = [word_in_list + end_string for word_in_list in old_list]
使用诸如“list”之类的名称作为变量名是不好的,因为它会覆盖/覆盖内置命令。
解决方案 11:
您可以在 python 中的 map 中使用 lambda。编写了一个格雷码生成器。https
://github.com/rdm750/rdm750.github.io/blob/master/python/gray_code_generator.py
# 您的代码放在此处 ''' n-1 位代码,每个单词前面都添加 0,后跟相反顺序的 n-1 位代码,每个单词前面都添加 1。'''
def graycode(n):
if n==1:
return ['0','1']
else:
nbit=map(lambda x:'0'+x,graycode(n-1))+map(lambda x:'1'+x,graycode(n-1)[::-1])
return nbit
for i in xrange(1,7):
print map(int,graycode(i))
解决方案 12:
list2 = ['%sbar' % (x,) for x in list]
不要用作list
名称;它会遮蔽内置类型。
解决方案 13:
万一
list = ['foo', 'fob', 'faz', 'funk']
string = 'bar'
for i in range(len(list)):
list[i] += string
print(list)