我试图采取一个字符串,并将其附加到每个字符串包含在一个列表,然后有一个新的列表与完成的字符串。例子:

list1 = ['foo', 'fob', 'faz', 'funk']
string = 'bar'

*magic*

list2 = ['foobar', 'fobbar', 'fazbar', 'funkbar']

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


当前回答

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

不要用list作为名字;它隐藏内置类型。

其他回答

结合地图和格式:

>>> list(map('{}bar'.format,  ['foo', 'fob', 'faz', 'funk']))
['foobar', 'fobbar', 'fazbar', 'funkbar']

因此,没有循环变量。 它适用于Python 2和Python 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']

这里有一个简单的答案,用熊猫。

import pandas as pd
list1 = ['foo', 'fob', 'faz', 'funk']
string = 'bar'

list2 = (pd.Series(list1) + string).tolist()
list2
# ['foobar', 'fobbar', 'fazbar', 'funkbar']

扩展位到“追加一个字符串列表到一个字符串列表”:

    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

以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

你可以在python中使用lambda inside 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))