我们可以在python列表上执行replace吗?你知道吗
我有从csv文件导入的列表:
[['1', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0'], ['2', '0', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0'], ['3', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0']]
上面列表中的第一个索引(标记为粗体)将成为客户id,然后是他们购买的商品,从上面的列表中我们可以看到第12列中客户1购买的商品用斜体标记。你知道吗
我们的愿望是:
costumer 1 purchased item 12 and item 22 and so it's for costumer 2 and 3
注意,我尝试过使用panda而不是work,我不知道如何在for循环中使用if语句。你知道吗
另外,我还使用了rappid minner,它们逐列替换,并包含了要替换的[0][0]。除了python还有其他解决方案吗?你知道吗
这是我的密码:
import csv
csvfile = open("tran.csv", 'r')
reader = csv.reader(csvfile, delimiter=',')
my_list = list(reader)
a = len(my_list[1])
b = (my_list)
x=0
y=0
for name in my_list:
print ("costummer", my_list[0][0], "buy", my_list[n][g])
csv writer更新:
csvdict = {words[0]:words[1:] for words in csv}
for x in csvdict.keys(): # iterate over the keys '1', '2', ....
products = [index+1 for index,v in enumerate(csvdict[x]) if v == '1' ] # create list of purchases where the '1's are indexed
f = open("trans.csv", 'w')
result = ("costummer", x, "buy", products)
resultstr = (','.join([str(x) for x in hasil]))#I try to convert it to str.
print (resultstr) #to check whether the conversion from list into str is working or not.
f.write(resultstr) #try to write to csv file
这是一个“起点”,将有一个额外的索引为客户1,这是你可以玩的东西。这可能并不重要。您可以添加if子句来处理它。你知道吗
相关问题 更多 >
编程相关推荐