簡體   English   中英

允許用戶輸入單詞的列表位置以返回到列表中的第二和第三元素

[英]Allow the user to input the list position of the word to RETURN to 2nd and 3rd element from the list

我需要有人幫助我,而無需使用外部庫對此進行編碼熊貓進口異常計數器

lineList = [['Cat', 'c', 1, x],['Cat', 'a', 2, x],['Cat', 't', 3, x],['Bat', 'b', 1, 3],['Bat', 'b', 1, 2],['Mat', 'm', 1, 1],['Fat', 'f', 1, 13]]

二維列表中出現次數超過2次的單詞顯示在數字列表中

例如:

1. Cat
2. Bat

如何允許用戶通過輸入列表位置編號來選擇單詞? 因此,例如,如果用戶輸入1,它將在嵌套列表中返回Cat的第二個和第三個元素:

c = 1, a = 2, t = 3

我是Python的初學者,所以不確定如何解決此問題。

您可以使用str.joinstr.formatenumerate和一個生成器表達式

word_counts = [['Cat', 2], ['Bat', 3], ['Fat', 1], ['Mat', 1]]

filtered = [p for p in word_counts if p[1] > 1]

print('\n'.join('{0}. {1}'.format(i, p[0]) for i, p in enumerate(filtered, 1)))

輸出:

1. Cat
2. Bat

對於特定位置的字符串:

n = int(input('position: '))   #   1-indexed

print('{0}. {1}'.format(n, filtered[n - 1][0]))   #   0-indexed (hence, n - 1)

使用Counter對單詞進行計數,然后使用enumerate為列表添加數字:

from collections import Counter

lineList = [['Cat', 'c', 1, 2],['Cat', 'c', 1, 3],['Bat', 'b', 1, 4],['Bat', 'b', 1, 3],['Bat', 'b', 1, 2],['Mat', 'm', 1, 1],['Fat', 'f', 1, 13]]

counts = Counter(word for word, *other_stuff in lineList)

filtered = [word for word, count in counts.items() if count >= 2]

for number, word in enumerate(filtered, start=1):
    print("{: >2}.".format(number), word)

版畫

 1. Cat
 2. Bat

如果您無法導入Counter ,則可以很容易地編寫一個基本的替代品:

def Counter(seq):
    d = {}
    for item in seq:
        d[item] = d.get(item, 0) + 1
    return d

Counter具有更多功能,但這就是我們正在使用的全部)

然后,您可以選擇一個單詞:

def choose(filtered):
    while True:
        choice = input("Select a word: ")
        try:
            choice = int(choice)
            return filtered[choice-1]
        except ValueError, IndexError:
            print("Please enter a number on the list")

您就在那里,只需檢查嵌套列表中第二項的值是否大於1。

list1 = [['Cat', 2], ['Bat', 3], ['Fat', 1], ['Mat', 1]]

index = 1
for i in range(len(list1)):
    if list1[i][1] > 1:
        print (str(index)+ ". " + str(list1[i][0]))
        index += 1

打印:

1. Cat
2. Bat

您對說明做了一些更改,所以我重寫了答案以使其更合適

lineList = [['Cat', 'c', 1, 'x'],['Cat', 'a', 2, 'x'],['Cat', 't', 3, 'x'],['Bat', 'b', 1, 3],['Bat', 'b', 1, 2],['Mat', 'm', 1, 1],['Fat', 'f', 1, 13]]


#First we create a dictionary with the repeating words in the list you gave
nameList = []    
frequencyDict = {}
for i in range(len(lineList)):

    if lineList[i][0] in frequencyDict.keys():
        frequencyDict[lineList[i][0]] += 1
    else:
        frequencyDict[lineList[i][0]] = 1

    #this will give you a list with the order
    #it will be useful to get the indices of the repeating word later
    nameList.append(lineList[i][0]) 


# Printing a list of values when if they are repeated
index = 1
repeats = []
for i in frequencyDict.keys():

    if frequencyDict[i] > 1: #This if statement checks if it was repeated or not

        print(str(index)+ ". " + i)
        repeats.append(i) # we also crete yet another list so the user can call it with his input later
        index += 1



x = (int(input("Which item on the list would you like to know more information about: \n")) -1) #note that we are subtracting one from the input so it matches the index of the list

# Here I am trying to get all the indices that start with the word that user replied
indicesList = []
for i in range(len(nameList)):
    if nameList[i] == repeats[x]:
        indicesList.append(i)

# Here I am printing the value that is in the index 1 and 2 of the nested list in Linelist
for i in range(len(indicesList)):
    print(str(lineList[indicesList[i]][1]) +
        " = " +
        str(lineList[indicesList[i]][2]))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM