Python不能在lis中打印特定的值

2024-09-30 08:29:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个用户给定的年间隔(例如1998-2017年),必须从列表“mlist”中打印特定值,该列表包含给定间隔中的任何年份。在“plist”中按索引打印出书名。 问题是,它无法在名单中找到具体年份,但它无论如何都在那里

已经尝试过用range(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”]

它必须在用户指定的时间间隔内打印年份和书籍


Tags: the用户in列表for间隔rangeint
3条回答

您没有指定mlistplist列表的结构,但我怀疑您应该print(plist[value], 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

{cd1>这是一个问题。但是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

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

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

顺便说一句: 您可能不需要continue语句-在本例中它不起任何作用。在

相关问题 更多 >

    热门问题