English 中文(简体)
采用同样的措辞,列入在沙捞越的浮雕清单
原标题:Appending the same string to a list of strings in Python
  • 时间:2010-01-12 16:50:17
  •  标签:
  • python
  • list

我正试图作一个扼杀,并将之附在一份清单中的每一条插图上,然后有一份新清单,其中附有完整的插图。 例:

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

*magic*

list2 = [ foobar ,  fobbar ,  fazbar ,  funkbar ]

我曾尝试过路,试图列出谅解,但这是垃圾。 一如既往,任何帮助都受到高度赞赏。

最佳回答

这样做的最简单方式是罗列:

[s + mystring for s in mylist]

通知说,我避免使用诸如<代码>>><>>>/代码”等已建名称,因为这种影子或隐藏了所建名称,这并不好。

此外,如果你实际上不需要清单,但仅仅需要一个召集人,则发电机的表述可以提高效率(尽管在短名单上不可能如此):

(s + mystring for s in mylist)

这些都是非常有力、灵活和简明的。 每名优秀学生都应学会学习,以学习他们。

问题回答
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 
list2 = list(map(lambda orig_string: orig_string + string, my_list))

,关于功能性方案拟订工具的一节<>,供更多实例使用map

此处采用<代码>pandas的简单答案。

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

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

www.un.org/Depts/DGACM/index_spanish.htm 更新更多备选办法

以下是我所遵循的一些方法,我确信,可能有更多的方法。

<><><>>Method 1:>>>

list1 = [ foo ,  fob ,  faz ,  funk ]
list2 = [ls+"bar" for ls in list1] # using list comprehension
print(list2)

<><><>>Method2:>>>

list1 = [ foo ,  fob ,  faz ,  funk ]
list2 = list(map(lambda ls: ls+"bar", list1))
print(list2)

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

<><><>Method 4:>>

list1 = [ foo ,  fob ,  faz ,  funk ]
addstring =  bar 
list2 = []
for value in list1:
    list2.append(str(value) + "bar")
print(list2)

<><><>Method 5:>>

list1 = [ foo ,  fob ,  faz ,  funk ]
list2 = list(map(  .join, zip(list1, ["bar"]*len(list1))))
print(list2)

避免使用关键词作为清单等变数,改称清单1

3. 试验如下:

[s + mystring for s in mylist]

似乎比明显使用像样的休闲设施要快35%:

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

缩略语:

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

Thus, there is no loop variable.
It works for Python 2 and 3. (In Python 3 one can write [*map(...)], and in Python 2 just map(...).

如果赞成模块表达

>>> list(map( %sbar .__mod__,  [ foo ,  fob ,  faz ,  funk ]))
[ foobar ,  fobbar ,  fazbar ,  funkbar ]

<<>prepend/strong>, 可查阅__add__<>>>。 方法

>>> list(map( bar .__add__,  [ foo ,  fob ,  faz ,  funk ]))
[ barfoo ,  barfob ,  barfaz ,  barfunk ]

将范围扩大至“将示意图清单列入示意图清单”:

    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)

d 粉碎机可进一步改装

new_list = [word_in_list + end_string for word_in_list in old_list]

使用“名单”等贵方变量名称是不好的,因为清单将超出建筑群。

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

由于使用窒息法的3.6是最佳做法(而不是<代码>format或与+保持一致)。 见PEP498

list1 = [ foo ,  fob ,  faz ,  funk ]
mystring =  bar 

list2 = [f"{s}{mystring}" for s in list1]
list2 = [ %sbar  % (x,) for x in list]

并且不使用<代码>>list作为名称;它为所建类型投影。

案情陈述

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




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签