问题:在Python中将相同的字符串追加到字符串列表

我正在尝试采用一个字符串,并将其附加到列表中包含的每个字符串中,然后使用完成的字符串创建一个新列表。例:

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

*magic*

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

我尝试了循环,并尝试了列表理解,但这是垃圾。一如既往的任何帮助,不胜感激。

I am trying to take one string, and append it to every string contained in a list, and then have a new list with the completed strings. Example:

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

*magic*

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

I tried for loops, and an attempt at list comprehension, but it was garbage. As always, any help, much appreciated.


回答 0

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

[s + mystring for s in mylist]

请注意,我避免使用内置名称,list因为那样会掩盖或隐藏内置名称,这非常不好。

另外,如果您实际上不需要列表,而只需要一个迭代器,则生成器表达式可以更有效(尽管在短列表中这并不重要):

(s + mystring for s in mylist)

这些功能非常强大,灵活且简洁。每个好的python程序员都应该学会使用它们。

The simplest way to do this is with a list comprehension:

[s + mystring for s in mylist]

Notice that I avoided using builtin names like list because that shadows or hides the builtin names, which is very much not good.

Also, if you do not actually need a list, but just need an iterator, a generator expression can be more efficient (although it does not likely matter on short lists):

(s + mystring for s in mylist)

These are very powerful, flexible, and concise. Every good python programmer should learn to wield them.


回答 1

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']
my_list = ['foo', 'fob', 'faz', 'funk']
string = 'bar'
my_new_list = [x + string for x in my_list]
print my_new_list

This will print:

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

回答 2

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

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

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

map seems like the right tool for the job to me.

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

See this section on functional programming tools for more examples of map.


回答 3

以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

Running the following experiment the pythonic way:

[s + mystring for s in mylist]

seems to be ~35% faster than the obvious use of a for loop like this:

i = 0
for s in mylist:
    mylist[i] = s+mystring
    i = i + 1

Experiment

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)

Results

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

回答 4

扩展到“将字符串列表追加到字符串列表”:

    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

Extending a bit to “Appending a list of strings to a list of strings”:

    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)

Result:

array(['a@1', 'b@2', 'c@3', 'd@4', 'e@5'], dtype=object)

dtype odject may be further converted str


回答 5

您可以在python地图中使用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))

you can use lambda inside map in python. wrote a gray codes generator. https://github.com/rdm750/rdm750.github.io/blob/master/python/gray_code_generator.py # your code goes here ”’ the n-1 bit code, with 0 prepended to each word, followed by the n-1 bit code in reverse order, with 1 prepended to each word. ”’

    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))

回答 6

更新更多选项

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

避免将关键字用作“列表”之类的变量,而应将“列表”重命名为“ list1”

Updating with more options

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

Avoid using keywords as variables like ‘list’, renamed ‘list’ as ‘list1’ instead


回答 7

这是使用的简单答案pandas

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

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

Here is a simple answer using pandas.

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

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

回答 8

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

并且不要使用list名字;它隐藏了内置类型。

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

And don’t use list as a name; it shadows the built-in type.


回答 9

new_list = [word_in_list + end_string for word_in_list in old_list]

为变量名使用“ list”之类的名称是不好的,因为它将覆盖/覆盖内置函数。

new_list = [word_in_list + end_string for word_in_list in old_list]

Using names such as “list” for your variable names is bad since it will overwrite/override the builtins.


回答 10

以防万一

list = ['foo', 'fob', 'faz', 'funk']
string = 'bar'
for i in range(len(list)):
    list[i] += string
print(list)

Just in case

list = ['foo', 'fob', 'faz', 'funk']
string = 'bar'
for i in range(len(list)):
    list[i] += string
print(list)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。