简体   繁体   中英

Python How to sort list in a list

I'm trying to sort a list within a list. This is what I have. I would like to sort the inner namelist based on alphabetical order. Have tried using loops but to no avail. The smaller 'lists' inside happens to be strings so I can't sort() them as list. Error: 'str' object has no attribute 'sort'

Names = [
    [['John'] ['Andrea', 'Regina', 'Candice'], ['Charlotte', 'Melanie'], 
    ['Claudia', 'Lace', 'Karen'] ['Ronald', 'Freddy'], 
    ['James', 'Luke', 'Ben', 'Nick']]
]

I would like it to be sorted into:

[
    [['John'] ['Andrea', 'Candice', 'Regina'], ['Charlotte', 'Melanie'], 
    ['Claudia', 'Karen', 'Lace'] ['Freddy', 'Ronald'], 
    ['Ben', 'James', 'Luke', 'Nick']]
]

Thank you. Edit: Sorry i made a mistake in the previous codes. Ive since edited it.

Names = [sorted(sublist) for sublist in Names]

This is a list comprehension that takes each sublist of Names , sorts it, and then builds a new list out of those sorted lists. It then makes Names that list

The built - in list method: sort() works in-place on sub lists if you iterate over them:

Names = [['John', 'Andrea', 'Regina', 'Candice', 'Charlotte', 'Melanie'], ['Claudia', 'Lace', 'Karen', 'Ronald', 'Freddy'], ['James', 'Luke', 'Ben', 'Nick']

for sublist in Names:
    sublist.sort()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM