1

list=[[AA,'1'] ,[BB,'4'] ,['CC','3']]

I want expand list[0] of count list[1]

Expected output: ['AA','BB','BB','BB','BB','CC','CC','CC']

I try below 2 ways but not works... Please could tell me where i need to fix?

⓵
variableName = []
         for row in rows:
            vName = row[0]
            count = int(row[1])
                          
            result = Counter(vName=count)
            variableName.append(list(result.elements()))

⓶
variableName = []
         for row in rows:
            vName = row[0]
            count = int(row[1])
      while count < countRW:
                variableName.append(vName) 
2
  • 1
    You are making it harder than it should be. Try simplifying like: [i for i, n in list1 for _ in range(int(n))]? Commented Aug 3, 2021 at 9:22
  • First time i try python thats why i don`t know some keyword.. Thanks for your answer i will try that way Commented Aug 5, 2021 at 0:34

2 Answers 2

1

Your first approach would work if you construct the Counter object properly by passing a dict object instead of a keyword argument with a fixed name, and if you call list.extend instead to avoid nesting the list:

for row in rows:
    vName = row[0]
    count = int(row[1])
    result = Counter({vName: count})
    variableName.extend(list(result.elements()))

Your second approach would work if you keep decreasing the counter in the while loop and exit the loop when the counter reaches 0:

for row in rows:
    vName = row[0]
    count = int(row[1])
    while count > 0:
        variableName.append(vName)
        count -= 1
Sign up to request clarification or add additional context in comments.

Comments

1

First of all the list you have given isn't in correct format. It should be likelist1 =[['AA','1'] ,['BB','4'] ,['CC','3']]

After that you can use the output function and pass your desired list as an argument you will get an list in return :

list1 =[['AA','1'] ,['BB','4'] ,['CC','3']]

def output(rows):
    variableName = []
    for row in rows:
        vName = row[0]
        count = int(row[1])
        for num_of_element in range(count):
            variableName.append(vName)
    return variableName

print(output(list1))

2 Comments

Thanks for quick answer. when i use that i get error "TypeError: 'list' object cannot be interpreted as an integer".
I have edited the answer. This time you shouldn't get any Error. Try to understand the code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.