简体   繁体   中英

How to reverse each item in the nested list?

Lists are used to store multiple items in a single variable. Lists are created using square brackets.

I want to reverse each item in the list of a list.

I tried reversed and [::1] method but it did not gave me desired output.

Here is my list
list1 = [1, 2, 3, [4, 5, 6], 6, 7, [8, 9, 10]]

I tried print(list1[::-1]) and reversed(list1) and got this output

output: [[8, 9, 10], 7, 6, [4, 5, 6], 3, 2, 1]

How could I get this output?

output: [[10, 9, 8], 7, 6, [6, 5, 4], 3, 2, 1]

You can use a recursive function.

def revall(l):
    return [revall(x) if isinstance(x, list) else x for x in l[::-1]]
print(revall([1, 2, 3, [4, 5, 6], 6, 7, [8, 9, 10]]))

Try this one:

list1 = [1, 2, 3, [4, 5, 6], 6, 7, [8, 9, 10]]
list1.reverse()
for sub_list in list1:
  if type(sub_list) is list:
        sub_list.reverse()
print(list1)

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