简体   繁体   中英

Re-Arrange rows in two-dimensional arrays without numpy

Rows in a 2D array are re-arranged according to the number of "*" in each row.

Example:

My array:

[['*', '-', '*', '*', '*', '*'],
 ['*', '-', '-', '*', '-', '-'],
 ['-', '*', '*', '-', '-', '-'],
 ['*', '-', '*', '*', '-', '-'],
 ['-', '-', '*', '*', '*', '*']]

Expected output:

[['*', '-', '*', '*', '*', '*'],
 ['-', '-', '*', '*', '*', '*'],
 ['*', '-', '*', '*', '-', '-'],
 ['*', '-', '-', '*', '-', '-'],
 ['-', '*', '*', '-', '-', '-']]

The row with the greatest number of * will be arranged first, while the row with the least number of - will be arranged last. If rows have the same amount of * , the relative ordering is maintained.

Sorting with an appropriate key function will do:

array = [['*', '-', '*', '*', '*', '*'],
         ['*', '-', '-', '*', '-', '-'],
         ['-', '*', '*', '-', '-', '-'],
         ['*', '-', '*', '*', '-', '-'],
         ['-', '-', '*', '*', '*', '*']]

array.sort(key=lambda a: a.count('*'), reverse=True)
array
#[['*', '-', '*', '*', '*', '*'],
# ['-', '-', '*', '*', '*', '*'],
# ['*', '-', '*', '*', '-', '-'],
# ['*', '-', '-', '*', '-', '-'],
# ['-', '*', '*', '-', '-', '-']]

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