Answer the question
In order to leave comments, you need to log in
Why are all list dictionaries empty except the first one?
It is necessary to write to the file user_id; category, 1, but only the 1st user is correctly recorded
import csv
def writer(user_id):
user_cart = []
user_order = []
user_cart_quantity = {} # {user_cart: user_order}
for row in reader:
if row['user_id'] == str(user_id):
# список со всеми категориями с повтором
user_cart.append(row['cart'])
# список уникальных дат заказов
if row['order_completed_at'] not in user_order:
user_order.append(row['order_completed_at'])
# получение словаря key - категория, value - количество заказов
for i in user_cart:
if i not in user_cart_quantity:
if user_cart.count(i) > len(user_order) / 2: # заказов > 50%
user_cart_quantity.update({f'{i}': user_cart.count(i)})
with open('data/tesr.txt', 'a') as fw:
fw.write(f'{user_id};{i}, 1\n')
print(user_id)
print(user_order)
print(len(user_order))
print(user_cart_quantity)
with open('data/train.csv') as f:
reader = csv.DictReader(f)
user_id = 2
while user_id < 20000:
writer(user_id)
user_id += 1
Answer the question
In order to leave comments, you need to log in
in each cycle, reset the file pointer to the beginning f.seek(0)
ps What you have written is a complete nightmare. can be optimized by making only 1 pass through the file
You are using the global reader object. After the first user, the reader has reached the end of the file and has nothing more to read.
Change the code so that each user has their own dictionary, and sort the data into them. For example, make a top-level dictionary where the key is user_id.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question