简体   繁体   中英

Sort list so large strings are not next to large strings. (Python)

I'd like to sort a lists of strings the following way:

input_list = ["1", "22", "333", "4444"] # This list can have an odd amount of items.

# Some code

output_list = ["4444", "22", "333", "1"]

The only thing I need is to sort a list so I do not get a large length string next to another large size string.

This sure will not always be possible due to having not enough large or small strings, but the sorting algorithm should try to not have that many large strings next to other large strings.

Thanks in advance.

One approach would be to sort list by length first and then form a new list where elements are taken from opposite ends of new list. This way you will have the longest available item followed by the shortes available.

input_list = ["1", "22", "333", "4444"]
sorted_by_len = sorted(input_list, key=len)
output = []
for i in range(len(sorted_by_len) // 2):
    output.append(sorted_by_len.pop())
    output.append(sorted_by_len.pop(0))
if sorted_by_len:   # if len was odd, have to deal with last element
    output += sorted_by_len

Result for given input:

['4444', '1', '333', '22']

I looked at the two answers above and wanted to give you something that a newbie would understand. It joins the good parts of the two answers above. I hope you find it helpful.

input_list = ["1", '55555', "22", "333", "4444"]
j = len(input_list)-1
input_list = sorted(input_list, key=len)
output_list = []
limits = len(input_list)//2
for i in range(len(input_list)//2):
    output_list.append(input_list[j])
    j = j - 1
    output_list.append(input_list[i])
    i = i + 1
    if i == limits and len(input_list) % 2 == 1:
        output_list.append(input_list[j])
print(output_list)

It tries to simplify the two parts although longer.

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