开发者

Perform a string operation for every element in a Python list

开发者 https://www.devze.com 2023-03-29 03:31 出处:网络
I have a list of strings in Python - elements. I would like to edit each element in elements. See the code below (it doesn\'t work, but you\'ll get the idea):

I have a list of strings in Python - elements. I would like to edit each element in elements. See the code below (it doesn't work, but you'll get the idea):

for element in elements:
    element = "%" + element + "%"

Is开发者_运维百科 there a way to do this?


elements = ['%{0}%'.format(element) for element in elements]


You can use list comprehension:

elements = ["%" + e + "%" for e in elements]


Python 3.6+ version (f-strings):

elements = [f'%{e}%' for e in elements]


You can use list comprehensions:

elements = ["%{}%".format(element) for element in elements]


There are basically two ways you can do what you want: either edit the list you have, or else create a new list that has the changes you want. All the answers currently up there show how to use a list comprehension (or a map()) to build the new list, and I agree that is probably the way to go.

The other possible way would be to iterate over the list and edit it in place. You might do this if the list were big and you only needed to change a few.

for i, e in enumerate(elements):
    if want_to_change_this_element(e):
        elements[i] = "%{}%".format(e)

But as I said, I recommend you use one of the list comprehension answers.


elements = map(lambda e : "%" + e + "%", elements)


Here some more examples

char = ['g:', 'l:', 'q:']

Using Replace

for i in range(len(char)):
    char[i] = char[i].replace(':', '')

Using strip

for i in range(len(char)):
    char[i] = char[i].strip(':')

Using a function

def list_cleaner(list_):
    return [char_.strip(':') for char_ in list_]


new_char = list_cleaner(char)
print(new_char)

Using Generator function(adviced if you have a large piece of data)

def generator_cleaner(list_):
    yield from (char_.strip(':') for char_ in list_)

# Prints all results in once
gen_char = list(generator_cleaner(char))

# Prints as much as you need, in this case only 8 chars
# I increase a bit the list so it makes more sense
char = ['g:', 'l:', 'q:', 'g:', 'l:', 'q:', 'g:', 'l:', 'q:']

# let's call our Generator Function
gen_char_ = generator_cleaner(char)

# We call only 8 chars
gen_char_ = [next(gen_char_) for _ in range(8)]
print(gen_char_)
0

精彩评论

暂无评论...
验证码 换一张
取 消