Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

Python: appending same string to list by n times

I have given csv file which I divided into rows with semicolons. Each row has a place, product name and amount. It was pretty easy to add each product to list if the amount was 1. But when the amount is >1, then comes the problem. Dictionary is for counting how many times the item is given in the list. For example:

I have a row where: Test; Chicken bowl; 4;

name = Test, item = chicken bowl, amount = 4

if name =='Test':
    if amount == 1:
       count_test += 1
       test_items.append(item)
    else:
       count_test += 1
       test_items.append(int(amount) * item)
       #listt = [item] * int(amount)
       #test_items.append(listt) 
       print(f'Test checked and count {count_test}')
       print(f' {item}; {amount}; ')
items_dict = {x:test_items.count(x) for x in test_items}
    print(f'Test: {items_dict}')

The desired result should be:

  • I have list:
['FIT salmon bowl 375 kcal', 'Sushi Rice', 'Extra avocado', 'Chicken bowl', 
'Sushi Rice', 'Extra coriander', 'Extra avocado', 'Chicken bowl',
'Chicken bowl','Chicken bowl','Chicken bowl','Chicken bowl', 'Sushi Rice',
 'Salmon bowl','Salmon bowl' 'Sushi Rice', 'Salmon bowl',
'Salmon bowl', 'Quinoa', 'FIT salmon bowl 375 kcal', 'Quinoa']
  • To dictionary to get the count of each key:
Test: {'FIT salmon bowl 375 kcal': 2,
 'Sushi Rice': 4, 'Extra avocado': 2, 'Extra coriander': 1, 
'Chicken bowl': 5, 'Salmon bowl': 4, 'Quinoa': 2}

But not like this which I have at the moment:

  • List:
['FIT salmon bowl 375 kcal', 'Sushi Rice', 'Extra avocado', 'Chicken bowl',
 'Sushi Rice', 'Extra coriander', 'Extra avocado', 
'Chicken bowlChicken bowlChicken bowlChicken bowl', 'Sushi Rice',
 'Salmon bowlSalmon bowl', 'Sushi Rice', 'Salmon bowlSalmon bowl', 
'Quinoa', 'FIT salmon bowl 375 kcal', 'Quinoa']
  • To dictionary:
Test: {'FIT salmon bowl 375 kcal': 2, 'Sushi Rice': 4, 'Extra avocado': 2,
 'Chicken bowl': 1, 'Extra coriander': 1, 
'Chicken bowlChicken bowlChicken bowlChicken bowl': 1, 
'Salmon bowlSalmon bowl': 2, 'Quinoa': 2}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.6k users

...