从列表中随机选择项目并存储索引

时间:2018-03-15 17:37:12

标签: python python-3.x

我有60部电影的清单。

films = ['x','y','z' ......]

我想随机选择5部这些影片供用户评分(从-5到5),并将这些评分存储在电影所在的同一索引中的新列表中。< / p>

例如,如果5部电影分别位于第0,第12,第15,第25和第56个索引中,那么它们将位于我的新列表中的这些位置,列表中的其余项目将为零。所以它看起来像

'Please rate the following films:'
harry potter: 3 #user inputs rating of 3 and so on
inception: 5
Disaster Move: -5
saw 2: 2 
interstellar: 4

为方便起见,让我们说电影恰好是电影列表中的第0,第2,第4,第5和第7个指数

 print(results)
 [3,0,5,0,-5,2,0,4,0,0,0,0,0,0,0,0,0,......] #all the way to 60 ratings

好的,现在我得到了

ratings[books.index(books[i])]=rate
TypeError: '_io.TextIOWrapper' object does not support item assignment

我的代码如下:

books = []
with open('books.txt') as b:
    for line in b:
        books.append(line)

if username in namesToRatings:
    print('We already have your data')
    userdata = {username:namesToRatings[username]}
else:
    print('We dont have your data')
    random_index=random.sample(range(0,59), 5)
    print(random_index)
    for i in random_index:
        rate=input(books[i]+" : Give Rating for this film from -5 to 5")
        ratings[books.index(books[i])]=rate
        print(ratings)

4 个答案:

答案 0 :(得分:0)

使用字典存储相对于电影的值

import random
films = ['Titanic', 'Hot Fuzz', 'RED', 'Inception', 'Waffles'] #for example
films_dict = {} #the key of the dictionary will be the film title, and the value of the key will be the rating the user gives, we will initialize the entries with a rating of 0.
for film in films:
    films[film] = 0 #create dictionary from existing list of films
for i in range(5): #ask the user 5 times to rate 5 different films and store their rating as a value to the key (films name) in our dictionary)
    film_to_rate = random.choice(films)
    rate = input('Please rate this film :', film_to_rate)
    films_dict[film_to_rate] = rate

虽然这个解决方案可以生成随机影片进行评分,但问题是可能会要求用户对同一部影片进行两次评分,您可以使用if else语句来检查影片是否已被评级,如果是我已经随机选择另一部电影进行评分,但我会把它留给你。

如果你想查看评级和电影吗......

for key, value in films_dict:
    print(key, value)

我建议使用字典来处理这些类型的东西,它们更容易操作而不是使用两个不同的列表,这些列表在上下文中将元素连接到元素,一个问题导致另一个问题。

答案 1 :(得分:0)

import random
import string
films = [''.join(random.choices(string.ascii_uppercase + string.digits, k=5)) for i in range(60)] #Generating 60 random string
ratings = [0 for i in range(60)] #Generating List of 60 Zeros
random_index=random.sample(range(0,59), 5)
print(random_index)
for i in random_index:
  rate=input(films[i]+" : Give Rating for this film from -5 to 5:")
  ratings[films.index(films[i])]=rate
print(ratings)

更正了您的代码:

import random
books = []
ratings = [0 for i in range(60)]
with open('books.txt') as b:
    for line in b:
        books.append(line.strip())
if username in namesToRatings:
    print('We already have your data')
    userdata = {username:namesToRatings[username]}
else:
    print('We dont have your data')
    random_index=random.sample(range(0,59), 5)
    print(random_index)
    for i in random_index:
      rate=input(books[i]+" : Give Rating for this film from -5 to 5")
      ratings[books.index(books[i])]=rate
      print(ratings)

答案 2 :(得分:0)

我猜你所坚持的部分是如何在同一时间跟踪电影和这些电影的索引。

如果是这样,技巧是enumerate

>>> a = ['a', 'b', 'c']
>>> for idx, value in enumerate(a): print(idx, value)
0 a
1 b
2 c

所以,然而你随机挑选了5部电影,从enumerate(films)中选出。

棘手的是,许多选择随机数的方法需要一个实际的序列,而enumerate不是一个序列。如果您收到TypeError: Population must be a sequence or set.之类的错误,那么您要做的是创建枚举对的临时列表:

enumerated_films = list(enumerate(films))

现在,无论你用什么来挑选5部随机影片,你都会得到5个随机(索引,电影)对。在那之后,一切都应该很容易。

答案 3 :(得分:0)

Siplyfied版本:

import random

films = [str(x) for x in range(1000,1000+60*50,50)] # 60 names 

# enumerate the names [ (0,'1000'),(1,'1050'),(2,'1100'),...,(58,'3900'), (59,'3950') ]
# sample 5 of the tuples (random choosing 5 without replacement)
# store int(input()) for the rating as (idx,rating) in a list
ratings = [(idx,int(input(f'\nRating for: {num}\t'))) for idx,num in \
           random.sample(list(enumerate(films)),k=5)]

# create enough zeros
zerofilled = [0 for x in range(len(films))]
# add all ratings to the zerofilled list
for idx,rat in ratings:
    zerofilled[idx]+=rat 

print(films)
print(zerofilled)

输出:

Rating for: 1500    8
Rating for: 1400    12
Rating for: 3150    9
Rating for: 1600    22
Rating for: 2450    3

['1000', '1050', '1100', '1150', '1200', '1250', '1300', '1350', 
 '1400', '1450', '1500', '1550', '1600', '1650', '1700', '1750', 
 '1800', '1850', '1900', '1950', '2000', '2050', '2100', '2150', 
 '2200', '2250', '2300', '2350', '2400', '2450', '2500', '2550', 
 '2600', '2650', '2700', '2750', '2800', '2850', '2900', '2950', 
 '3000', '3050', '3100', '3150', '3200', '3250', '3300', '3350', 
 '3400', '3450', '3500', '3550', '3600', '3650', '3700', '3750', 
 '3800', '3850', '3900', '3950']

[ 0, 0, 0, 0, 0, 0, 0, 0, 
 12, 0, 8, 0, 22, 0, 0, 0, 
  0, 0, 0, 0, 0, 0, 0, 0, 
 0, 0, 0, 0, 0, 3, 0, 0, 
 0, 0, 0, 0, 0, 0, 0, 0, 
 0, 0, 0, 9, 0, 0, 0, 0, 
 0, 0, 0, 0, 0, 0, 0, 0, 
 0, 0, 0, 0]

用户因输入失败而臭名昭着,因此您可能不希望将其作为1行列表补偿。