将相同的string追加到Python中的string列表中

我正在尝试一个string,并将其附加到列表中包含的每个string,然后有一个新的列表与完成的string。 例:

list = ['foo', 'fob', 'faz', 'funk'] string = 'bar' *magic* list2 = ['foobar', 'fobbar', 'fazbar', 'funkbar'] 

我尝试了循环,并尝试列表理解,但它是垃圾。 一如既往,任何帮助,非常感谢。

最简单的方法是使用列表理解:

 [s + mystring for s in mylist] 

请注意,我避免使用像list这样的内build名称,因为这会影响或隐藏内置名称,这是非常不好的。

另外,如果你实际上不需要一个列表,但是只需要一个迭代器,那么生成器expression式可以更有效率(尽pipe它在短列表中可能不重要):

 (s + mystring for s in mylist) 

这些function非常强大,灵活而简洁。 每个优秀的python程序员都应该学会如何使用它们。

 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'] 

直到现在,我还没有find方法来评论答案。 所以在这里。 我支持Ignacio Vazquez-Abrams的list2 = ['%sbar' % x for x in list]

其他人的答案是[string + "bar" for string in list]在大多数情况下都能正常工作,但是如果你接受一个更简单的解决scheme,那么就是遵循Pythondevise原则。 应该有一个明显的方法来做到这一点。 %sbar工作。

map对我来说似乎是正确的工具。

 my_list = ['foo', 'fob', 'faz', 'funk'] string = 'bar' list2 = map(lambda orig_string: orig_string + string, my_list) 

有关函数式编程工具的更多示例,请参见本节 。

 list2 = ['%sbar' % (x,) for x in list] 

不要用list作为名字; 它会隐藏内置的types。

 new_list = [word_in_list + end_string for word_in_list in old_list] 

使用诸如“list”这样的variables名是不好的,因为它会覆盖/覆盖内build的。

你可以在Python中使用lambda里面的map。 写了一个灰色代码生成器。 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)) 

以pythonic方式运行以下实验:

 [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