简体   繁体   中英

How do I make a list where each item occurs a different number of times?

I have two list one is list1=[], second is list2=["a","b","c"], I need to let list1=["a","a","a","b","b","c"], what should I do? In addition, the list2 can be anything , if it has 20 elements, the "a" should *20.

I know very little Python, so this might not be the best way of doing it, but it seems to work.

list1 = []
list2 = ["a", "b", "c"]
for x in range(len(list2)):
    list1 += [list2[x]] * (len(list2) - x)
print(list1)

Here's the same idea but with a one liner list comprehension:

list2 = ["a", "b", "c"]
list1 = [y for idx, x in enumerate(list2) for y in x * (len(list2) - idx)]
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