Removing character in list of strings

前端 未结 6 2106
清歌不尽
清歌不尽 2020-12-01 06:51

If I have a list of strings such as:

[(\"aaaa8\"),(\"bb8\"),(\"ccc8\"),(\"ffffdffffd8\")...]

What should I do in order to get rid of all the

相关标签:
6条回答
  • 2020-12-01 06:58

    Beside using loop and for comprehension, you could also use map

    lst = [("aaaa8"),("bb8"),("ccc8"),("ffffdffffd8")]
    mylst = map(lambda each:each.strip("8"), lst)
    print mylst
    
    0 讨论(0)
  • 2020-12-01 07:03
    lst = [("aaaa8"),("bb8"),("ccc8"),("ffffdffffd8")...]
    
    msg = filter(lambda x : x != "8", lst)
    
    print msg
    

    EDIT: For anyone who came across this post, just for understanding the above removes any elements from the list which are equal to 8.

    Supposing we use the above example the first element ("aaaaa8") would not be equal to 8 and so it would be dropped.

    To make this (kinda work?) with how the intent of the question was we could perform something similar to this

    msg = filter(lambda x: x != "8", map(lambda y: list(y), lst))
    
    • I am not in an interpreter at the moment so of course mileage may vary, we may have to index so we do list(y[0]) would be the only modification to the above for this explanation purposes.

    What this does is split each element of list up into an array of characters so ("aaaa8") would become ["a", "a", "a", "a", "8"].

    This would result in a data type that looks like this

    msg = [["a", "a", "a", "a"], ["b", "b"]...]

    So finally to wrap that up we would have to map it to bring them all back into the same type roughly

    msg = list(map(lambda q: ''.join(q), filter(lambda x: x != "8", map(lambda y: list(y[0]), lst))))
    

    I would absolutely not recommend it, but if you were really wanting to play with map and filter, that would be how I think you could do it with a single line.

    0 讨论(0)
  • 2020-12-01 07:15

    Try this:

    lst = [("aaaa8"),("bb8"),("ccc8"),("ffffdffffd8")]
    print([s.strip('8') for s in lst]) # remove the 8 from the string borders
    print([s.replace('8', '') for s in lst]) # remove all the 8s 
    
    0 讨论(0)
  • 2020-12-01 07:20
    mylist = [("aaaa8"),("bb8"),("ccc8"),("ffffdffffd8")]
    print mylist
    j=0
    for i in mylist:
        mylist[j]=i.rstrip("8")
        j+=1
    print mylist
    
    0 讨论(0)
  • 2020-12-01 07:20

    Here's a short one-liner using regular expressions:

    print [re.compile(r"8").sub("", m) for m in mylist]
    

    If we separate the regex operations and improve the namings:

    pattern = re.compile(r"8") # Create the regular expression to match
    res = [pattern.sub("", match) for match in mylist] # Remove match on each element
    print res
    
    0 讨论(0)
  • 2020-12-01 07:23

    A faster way is to join the list, replace 8 and split the new string:

    mylist = [("aaaa8"),("bb8"),("ccc8"),("ffffdffffd8")]
    mylist = ' '.join(mylist).replace('8','').split()
    print mylist
    
    0 讨论(0)
提交回复
热议问题