【发布时间】:2018-04-10 06:08:24
【问题描述】:
我们可以对 python 列表执行替换吗?
我有从 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 购买的商品,以斜体标记。
希望输出的是:
顾客 1 购买了商品 12 和商品 22,所以它是为顾客 2 和 3
请注意,我已经尝试使用 panda 并且无法正常工作,并且我不确定如何在 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 写入器更新:
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
【问题讨论】:
-
我很难理解你的英语。也许您可以编辑您的帖子以包含示例所需的输出?
-
@JohnGordon 编辑先生,希望比以前更好。
标签: python list pentaho data-cleaning