首页 > 解决方案 > Python 设置帮助

问题描述

所以我正在尝试制作一个推荐系统,但带有集合和文本文件。我目前有:

colours=["black","yellow","pink","gold","light red",
"turquoise","olive","orchid","brown","orange",
"purple","golden","light blue","sandy brown","spring green",
"maroon","gray","red","green","cyan","chocolate","salmon"]

user_rec=set()

for x in range (3):
  user=input(str(x+1)+". Enter the numbers of your 3 favourite colours:\n> ")
  print()
  user_rec.add(user)
print(user_rec)

with open("Colours.txt") as f:
    for line in f:
        fields=line.split(' ')
        colour1=int(fields[0])
        colour2=int(fields[1])
        colour3=int(fields[2])
        set(line).add(colour1)
        set(line).add(colour2)
        set(line).add(colour3)
        print(set(line))

其中 Colors 是包含 100 行 3 个随机生成的数字的文本文件,这些数字代表数组中的颜色。

该行的第一行是“8 9 17”,但是当我只想要 {8 ,9,17} 所以我可以将每条线集与用户集进行比较,以使用交集向他们推荐另一种颜色。

谁能告诉我我做错了什么?

标签: pythonset

解决方案


set(line)构造一行中所有字符的集合,这就是您打印的内容。你想做的是:

with open("Colours.txt") as f:
    for line in f:
        fields=line.strip().split() # you want to remove \n
        s = {int(item) for item in fields}
        print(s)

推荐阅读