Perform a string operation for every element in a Python list

前端 未结 5 1186
别跟我提以往
别跟我提以往 2020-11-28 23:42

I have an list of string elements in python elements and would like edit each element in elements with so I have a new element. See code below (it doesn\'t work

相关标签:
5条回答
  • 2020-11-29 00:02

    You can use list comprehension:

    elements = ["%" + e + "%" for e in elements]
    
    0 讨论(0)
  • 2020-11-29 00:04
    elements = ['%{0}%'.format(element) for element in elements]
    
    0 讨论(0)
  • 2020-11-29 00:06

    You can use list comprehensions:

    elements = ["%{}%".format(element) for element in elements]
    
    0 讨论(0)
  • 2020-11-29 00:14

    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.

    0 讨论(0)
  • 2020-11-29 00:23
    elements = map(lambda e : "%" + e + "%", elements)
    
    0 讨论(0)
提交回复
热议问题