How to convert elements in a list of list to lowercase?

后端 未结 3 1442
既然无缘
既然无缘 2021-01-16 09:04

I am trying to convert the elements of a list of list of lowercase. This is what is looks like.

print(dataset)
[[\'It\', \'went\', \'Through\', \'my\', \'shi         


        
相关标签:
3条回答
  • 2021-01-16 09:25

    If you wish to convert all the Strings in your list in Python, you can simply use following code:

    [w.lower() for w in My_List]
    

    My_List is your list name

    0 讨论(0)
  • 2021-01-16 09:27

    You have a nested structure. Either unwrap (if there is just one list contained, ever) or use a nested list comprehension:

    [[w.lower() for w in line] for line in dataset]
    

    The nested list comprehension handles each list in the dataset list separately.

    If you have just one list contained in dataset, you may as well unwrap:

    [w.lower() for w in dataset[0]]
    

    This produces a list with the lowercased strings directly contained, without further nesting.

    Demo:

    >>> dataset = [['It', 'went', 'Through', 'my', 'shirt', 'And', 'came', 'out', 'The', 'back', 'and', 'hit', 'the', 'kid', 'behind', 'me', 'in', 'the', 'toe']]
    >>> [[w.lower() for w in line] for line in dataset]
    [['it', 'went', 'through', 'my', 'shirt', 'and', 'came', 'out', 'the', 'back', 'and', 'hit', 'the', 'kid', 'behind', 'me', 'in', 'the', 'toe']]
    >>> [w.lower() for w in dataset[0]]
    ['it', 'went', 'through', 'my', 'shirt', 'and', 'came', 'out', 'the', 'back', 'and', 'hit', 'the', 'kid', 'behind', 'me', 'in', 'the', 'toe']
    
    0 讨论(0)
  • 2021-01-16 09:32

    Either use map

    map(str.lower,line)
    

    Or list comprehension (which is basically syntactic sugar)

    [x.lower() for x in line]
    

    And this process can be nested for the entire dataset

    [[x.lower() for x in line] for line in dataset]
    

    And if you want to join all lines into one, use reduce:

    reduce(list.__add__,[[x.lower() for x in line] for line in dataset])
    
    0 讨论(0)
提交回复
热议问题