允许用户将单词的列表位置输入 RETURN 到列表中的第 2 个和第 3 个元素

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

我需要有人帮助我在不使用外部库的情况下编写代码 panda imports exceptions counters

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

如何让用户通过输入列表位置编号来select一个词?因此,例如,如果用户输入 1,它将 return 嵌套列表中 Cat 的第二个和第三个元素:

c = 1, a = 2, t = 3

我是 Python 的初学者,所以不确定如何处理。

您可以使用 str.join, str.format, enumerate, and a generator expression:

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 有更多的功能,但这就是我们使用的全部)

然后您可以 select 一个单词:

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]))