Home > Software engineering >  How to make a new list from list of values of occurrences and value?
How to make a new list from list of values of occurrences and value?

Time:10-27

I have 2 lists one containing float values and second has number of occurrences of values from first list. How can I create a new list, that have value times occurrences?

values = [10.5,20.2, 50.0]
occ = [3,5,1]

Result should be [10.5,10.5,10.5,20.2,20.2,20.2,20.2,20.2,50.0]

CodePudding user response:

You can use zip to iterate both the lists in parallel, then just repeat the items number of times and add it to the resulting list, something like this:

result = []
for v,m in zip(values,occ):
    result.extend([v for _ in range(m)])
                  
result
[10.5, 10.5, 10.5, 20.2, 20.2, 20.2, 20.2, 20.2, 50.0]

Or the list-comprehension as suggested in comment:

[v for v, c in zip(values, occ) for _ in range(c)]
[10.5, 10.5, 10.5, 20.2, 20.2, 20.2, 20.2, 20.2, 50.0]

CodePudding user response:

You can use zip with a nested list comprehension:

values = [10.5,20.2, 50.0]
occ = [3,5,1]

result = [x for x, y in zip(values, occ) for _ in range(y)]

Alternatively, without using range:

result = [elem for x, y in zip(values, occ) for elem in [x] * y]

Output:

[10.5, 10.5, 10.5, 20.2, 20.2, 20.2, 20.2, 20.2, 50.0]

CodePudding user response:

You could use this:

sum(([v]*m for v, m in zip(values, occ)), [])

Not recommended for large lists. Actually not really recommended at all.

CodePudding user response:

The pythonic way would be using zip in a list comprehension as demonstrated multiple times.

You can simple loops and enumerate() to a similar effect - but it results in more lines of code:

values = [10.5,20.2, 50.0]
occ = [3, 5, 1]

result = []

# enumerate returns a tuple: position, value 
# of all values of the iterable you give it
for index, times in enumerate(occ):
    # use the index to get the value from the other list you 
    # have and append it multiple times
    for _ in range(times):
        result.append(values[index])

print(result)

Output:

[10.5, 10.5, 10.5, 20.2, 20.2, 20.2, 20.2, 20.2, 50.0]

See enumerate() documentation

  • Related