Python无法在列表中打印特定值

时间:2019-04-01 19:15:04

标签: python

我有一个给定的用户年间隔(例如1998-2017),并且必须从列表“ mlist”中打印特定值,该列表包含给定间隔中的任何年份。然后按“ plist”中的索引打印书名。 问题在于它无法在列表中找到该特定年份,但一定存在该位置

已经尝试通过使用范围(startingIn,EndingIn)进行for循环来做到这一点,但没有帮助

interval = input("Enter the range: ") #User selects specific interval

startingIn = int(interval.split('-')[0])
endingIn = int(interval.split('-')[1])

for x in range (int(startingIn), int(endingIn)):
    if x in mlist:
        value = mlist.index(x)    #mlist is the list which has years of the books
        print (value, x)       #plist is the list of books' names
    else:
        continue

plist = [“ book1”,“ book2”,“ book3”] mlist = [“ 1935”,“ 1990”,“ 1980”]

必须打印年份和包含用户给定间隔的书

3 个答案:

答案 0 :(得分:1)

您的问题是mlist是一个字符串列表。但是x是整数,而1935不是"1935",因此您永远不会与mlist.index(x)匹配。尝试将mlist转换为整数列表。

plist = ["book1", "book2", "book3"]
mlist = ["1935", "1990", "1980"]

interval = input("Enter the range: ") #User selects specific interval

startingIn = int(interval.split('-')[0])
endingIn = int(interval.split('-')[1])

nummlist = list(map(int, mlist))

for x in range (startingIn, endingIn+1): #no need to repeat int() here, and note +1 otherwise endingIn would not be included
    if x in nummlist:
        value = nummlist.index(x)
        print (plist[value], x)

这对我有用。它打印:

  

book1 1935
  book3 1980
  book2 1990

答案 1 :(得分:0)

mlist.index(x)返回元素的索引,因此您可能希望使用

index = mlist.index(x)
itemYouWant = plist[index]

顺便说一句: 您可能不需要继续语句-在这种情况下,它什么也不做。

答案 2 :(得分:0)

您未指定mlistplist列表的结构,但我怀疑您应该使用print(plist[value], x)而不是print(plist[x], x)

interval = input("Enter the range: ") # example "1990-2019"

bounds = interval.split("-")

for x in range(bounds[0], bounds[1]):
    if x in mlist:
        value = mlist.index(x)    #mlist is the list which has years of the books
        print (plist[value], x)       #plist is the list of books' names