Home > Software engineering >  How do you append a value to a list by a certain frequency?
How do you append a value to a list by a certain frequency?

Time:10-28

I'm writing a program to analyse a frequency table with different functions (mean, median, mode, range, etc) and I have the user inputting their data in two lists and then converting those answers into lists of integers

values_input = input('First, enter or paste the VALUES, separated by spaces (not commas): ')
freq_input = input('Now enter the corresponding FREQUENCIES, separated by spaces: ')
values = values_input.split()
freq = freq_input.split()
data_list = []

For every value, I want the program to append it to data_input by the corresponding frequency.

For example (desired result):

If values was: 1 2 3 4 and frequency was: 2 5 7 1

I want data_list to be: [1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4]

At the moment I have this:

for i in range(len(values)):
    j = 3
    while j != 0:
        data_input.append(values[i])
        j -= 1

But that only appends the values to data_input 3 times instead of the frequency

CodePudding user response:

a = input("First, enter or paste the VALUES, separated by spaces (not commas): ").split()
b = input("Now enter the corresponding FREQUENCIES, separated by spaces: ").split()
a = [int(i) for i in a]
b = [int(i) for i in b]
x = []
y = 0
for elem in a:
    temp = []
    temp.append(elem)
    x.append(temp * b[0 y])
    y  = 1
final = []
for lst in x:
    for elem in lst:
        final.append(elem)
print(final)

I am also a newbie. I know there are more efficient ways, but for now I have come up with this.

CodePudding user response:

You can use list multiplication to create a list of each value with the appropriate frequency:

values = [1,2,3,4]
freq = [2,5,7,1]

result = []
for i, v in enumerate(values):
    result  = [v] * freq[i]

Output:

[1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4]
  • Related