Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/293.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在未排序的列表中查找值_Python - Fatal编程技术网

Python 在未排序的列表中查找值

Python 在未排序的列表中查找值,python,Python,所以我有一个任务,就是告诉我编写一个关于食物的小测验。我经常问一些关于食物的随机问题,我必须展示他们回答的最推荐的食物中的两种。我列了一张8种食物的清单,并为每种食物打分 food=["pizza", "hotdogs", "chicken", "apples", "fish", "fries", "burgers", "donuts"]

所以我有一个任务,就是告诉我编写一个关于食物的小测验。我经常问一些关于食物的随机问题,我必须展示他们回答的最推荐的食物中的两种。我列了一张8种食物的清单,并为每种食物打分

food=["pizza", "hotdogs", "chicken", "apples", "fish", "fries", "burgers", "donuts"]
score=[0,0,0,0,0,0,0,0,0]

print("Please answer each of the questions with yes or no.")
question=input("Do you eat meat?")
if question=="yes":
score[0]=score[0] + 1
score[1]=score[1] + 1
score[2]=score[2] + 1
score[4]=score[4] + 1
score[6]=score[6] + 1
question=input("Do you like fruits?")
if question=="yes":
score[3]=score[3] + 1
question=input("Do you like fried foods?")
if question=="yes":
score[2]=score[2] + 1
score[5]=score[5] + 1
score[4]=score[4] + 1
question=input("Do you like cheese?")
if question=="yes":
score[0]=score[0] + 1
score[1]=score[1] + 1
score[6]=score[6] + 1
question=input("Do you like food with holes in it?")
if question=="yes":
score[7]=score[7] + 1
question=input("Do you like to eat healthy?")
if question=="yes":
score[3]=score[3] + 1
question=input("Do you like bread?")
if question=="yes":
score[1]=score[1] + 1
score[6]=score[6] + 1
question=input("Do you like protein rich foods?")
if question=="yes":
score[2]=score[2] + 1
score[4]=score[4] + 1
question=input("Do you like dessert?")
if question=="yes":
score[3]=score[3] + 1
score[7]=score[7] + 1
question=input("Are you a vegan?")
if question=="yes":
score[3]=score[3] + 1
score[5]=score[5] + 1
score[7]=score[7] + 1
print(food)
print(score)

biggestsofar=0
for i in range(1, len(score)):
if (score[biggestsofar] < score[i]):
    biggestsofar = i
print("The biggest value is", biggestsofar)
print("Your recommended food is", food[biggestsofar])
food=[“比萨饼”、“热狗”、“鸡肉”、“苹果”、“鱼”、“薯条”、“汉堡”、“甜甜圈”]
分数=[0,0,0,0,0,0,0,0,0]
打印(“请用是或否回答每个问题”)
问题=输入(“你吃肉吗?”)
如果问题==“是”:
分数[0]=分数[0]+1
分数[1]=分数[1]+1
分数[2]=分数[2]+1
分数[4]=分数[4]+1
分数[6]=分数[6]+1
问题=输入(“你喜欢水果吗?”)
如果问题==“是”:
分数[3]=分数[3]+1
问题=输入(“你喜欢油炸食品吗?”)
如果问题==“是”:
分数[2]=分数[2]+1
分数[5]=分数[5]+1
分数[4]=分数[4]+1
问题=输入(“你喜欢奶酪吗?”)
如果问题==“是”:
分数[0]=分数[0]+1
分数[1]=分数[1]+1
分数[6]=分数[6]+1
问题=输入(“你喜欢有洞的食物吗?”)
如果问题==“是”:
分数[7]=分数[7]+1
问题=输入(“你喜欢健康饮食吗?”)
如果问题==“是”:
分数[3]=分数[3]+1
问题=输入(“你喜欢面包吗?”)
如果问题==“是”:
分数[1]=分数[1]+1
分数[6]=分数[6]+1
问题=输入(“你喜欢富含蛋白质的食物吗?”)
如果问题==“是”:
分数[2]=分数[2]+1
分数[4]=分数[4]+1
问题=输入(“你喜欢甜点吗?”)
如果问题==“是”:
分数[3]=分数[3]+1
分数[7]=分数[7]+1
问题=输入(“你是素食主义者吗?”)
如果问题==“是”:
分数[3]=分数[3]+1
分数[5]=分数[5]+1
分数[7]=分数[7]+1
印刷品(食品)
打印(分数)
biggestsofar=0
对于范围(1,len(分数))内的i:
如果(得分[最大值]<得分[i]):
最大值=i
打印(“最大值为”,最大值为)
打印(“您推荐的食物是”,食物[最大的食物])

这就是我目前所拥有的。我正在努力展示推荐的两种食物。我发现了如何显示其中一个(即上面的代码^),但不知道如何显示第二个。我必须在他们回答问题时创建的列表中找到第二大数字。如果有人能帮助我,我将不胜感激。(是的,我不得不使用循环找到第一个问题)

我看错了你的问题。对不起:/ 好的,你想要两个最大的值,对吗?我的旧代码仍然有效,但经过一些修改。您需要找到该值的索引

lis = [0, 1, 3, 2, 1, 4, 3, 1, 9]
sorted_lis = sorted(lis)
print(lis.index(sorted_lis[-1]), lis.index(sorted_lis[-2]))
继续你的例子:

score = [0, 1, 3, 2, 1, 4, 3, 1, 9]
sorted_score = sorted(score)
print(food[score.index(sorted_score[-1])], food[score.index(sorted_score[-2])])
旁注 我不确定您是否了解类,但这里有一个更干净的替代解决方案:

class Food(): # create a food class
    def __init__(self, type_):
        self.type = type_
        self.value = 0

    def increment(self):
        self.value += 1

    def __lt__(self, other):
        return self.value < other.value

    def __le__(self, other):
        return self.value <= other.value

    def __gt__(self, other):
        return self.value > other.value

    def __ge__(self, other):
        return self.value >= other.value

    def __eq__(self, other):
        return self.type == other.type

foods = [Food("pizza"), Food("burger"), Food("hot dog")] # make some foods
food_STRING = []

for i in foods:
    food_STRING.append(i.type)

for i in range(10):
    food = input("Food:")
    foods[food_STRING.index(food)].increment()

sorted_food = sorted(foods)

print(sorted_food[-1].type, sorted_food[-2].type)
class Food():#创建一个Food类
定义初始化(自我,类型):
self.type=type_
self.value=0
def增量(自):
self.value+=1
定义(自身、其他):
返回self.value=其他.value
定义(自身、其他):
返回self.type==other.type
食物=[食物(“比萨饼”)、食物(“汉堡”)、食物(“热狗”)#制作一些食物
食物字符串=[]
对于我在食品方面:
food_STRING.append(i.type)
对于范围(10)内的i:
食物=输入(“食物:”)
食品[食品索引(食品)]增量()
已分类的食物=已分类的(食物)
打印(已分拣食物[-1]。类型,已分拣食物[-2]。类型)

您可以将答案想象为有两个存储桶,您可以为其分配一个更大的值,该值是当前存储桶的值,然后检查其中一个是否大于另一个,如果是,则交换它们。我假设您的作业不允许使用
排序
/
排序
功能:

largest, second_largest = (0, 0)
for item in range(len(score))):
    if score[item] > score[largest]:
        second_largest = largest
        largest = item
    elif score[largest] > score[item] > score[second_largest]:
        second_largest = item
print("The biggest value is", score[largest])
print("Your recommended food is", food[largest])
print("The second biggest value is", score[second_largest])
print("Your second recommended food is", food[second_largest])

虽然其他人给出了很好的答案,但我建议你使用字典。字典是指将一个值(通常是字符串)对应于另一个值(例如布尔值、数字或其他字符串)

我认为您应该在代码中实现这一点:

# Creating a dictionary (food: score)
my_dictionary = {
    'pizza': 0,
    'hotdogs': 0,
    'chicken': 0,
    'apples': 0,
    'fish': 0,
    'fries': 0,
    'burgers': 0,
    'donuts': 0,
}

# Creating a function to change the food and score. 
# Execute this function to change your score
def change_score(food, score):
    global my_dictionary
    my_dictionary[food] = score
我会让你用这个来尝试自己完成你的程序,但这应该是有帮助的。 本网站应帮助您了解字典:

使用字典方法 虽然有一些有趣的方法可以解决这个问题,但我把食物和问题都拿了出来,把它们转换成字典来帮助你得到答案

第1步:将食物转换成字典作为键,并将值作为分数

步骤2:将所有问题转换成字典,作为键和值,作为需要评分的项目列表。使用食物列表作为索引来查找关键字和增量。您还可以将该值用作食物项列表

food=["pizza", "hotdogs", "chicken", "apples", "fish", "fries", "burgers", "donuts"]
food_score = {f:0 for f in food}
questions = {'Do you eat meat ? ':[0,1,2,4,6],
             'Do you like fruits ? ':[3],
             'Do you like fried foods ? ':[2,4,5],
             'Do you like cheese ? ':[0,1,6],
             'Do you like food with holes in it ? ':[7],
             'Do you like to eat healthy ? ':[3],
             'Do you like bread ? ':[1,6],
             'Do you like protein rich foods ? ':[2,4],
             'Do you like dessert ? ':[3,7],
             'Are you a vegan ? ':[3,5,7]}
              
print("Please answer each of the questions with yes or no.")

#iterate through all the questions. k is question, 
#and v is the elements that needs incremented
for k,v in questions.items():
    q = input(k)
    if q.lower() == 'yes':
        #if answer is yes, then increment each food item by 1
        for i in v: food_score[food[i]] +=1

#sort the dictionary by value, in reversed order so first value is highest score
ranked_food = sorted(food_score, key=food_score.get, reverse=True)

print ('The biggest value is : ',food_score[ranked_food[0]])
print ('Your recommended food is : ', ranked_food[0])

print ('The second biggest value is : ', food_score[ranked_food[1]])
print ('Your second recommended food is : ', ranked_food[1])
第3步:反复回答问题并提出问题

第四步:如果答案是肯定的,使用食物分数字典将食物增加1

第五步:按相反顺序对食物分数字典进行排序,以获得最重要的食物项目。前两个将是前两个食物项目

food=["pizza", "hotdogs", "chicken", "apples", "fish", "fries", "burgers", "donuts"]
food_score = {f:0 for f in food}
questions = {'Do you eat meat ? ':[0,1,2,4,6],
             'Do you like fruits ? ':[3],
             'Do you like fried foods ? ':[2,4,5],
             'Do you like cheese ? ':[0,1,6],
             'Do you like food with holes in it ? ':[7],
             'Do you like to eat healthy ? ':[3],
             'Do you like bread ? ':[1,6],
             'Do you like protein rich foods ? ':[2,4],
             'Do you like dessert ? ':[3,7],
             'Are you a vegan ? ':[3,5,7]}
              
print("Please answer each of the questions with yes or no.")

#iterate through all the questions. k is question, 
#and v is the elements that needs incremented
for k,v in questions.items():
    q = input(k)
    if q.lower() == 'yes':
        #if answer is yes, then increment each food item by 1
        for i in v: food_score[food[i]] +=1

#sort the dictionary by value, in reversed order so first value is highest score
ranked_food = sorted(food_score, key=food_score.get, reverse=True)

print ('The biggest value is : ',food_score[ranked_food[0]])
print ('Your recommended food is : ', ranked_food[0])

print ('The second biggest value is : ', food_score[ranked_food[1]])
print ('Your second recommended food is : ', ranked_food[1])
ranked_food
中的前两个元素应该为您提供每个推荐的前2种食物

此解决方案非常灵活,允许您扩展食物列表,也可以扩展问题集。代码的其余部分可以保持不变,并将找到前两个食物建议

用你现有的方法 如果不允许您使用新方法,您可以执行以下操作:

假设允许您使用zip:

score_food = [(s,f) for s,f in zip(score,food)]
如果不允许使用zip,请执行以下操作:

score_food = []
for i in range(len(food)):
    score_food.append((score[i],food[i]))
现在使用以下命令按降序排列列表:

score_food.sort(reverse=True)
这将按降序给出分数。因为您将它们存储为元组,所以分数和食物将配对在一起,您可以使用索引识别它们中的每一个

score\u food[0]
排名最高
score\u food[0][0]
将是分数,
score\u food[0][1]
将是食物

同样地,
score\u food[1]
排名第二
score_food[1][0]
将是该得分,并且将以
score_ufood[1][1]
作为食物

如果不允许使用排序功能,请使用任何排序逻辑
for i in range (len(score_food)-1):
    for j in range(i+1,len(score_food)):
        if score_food[i][0] < score_food[j][0]:
            score_food[i],score_food[j] = score_food[j],score_food[i]