【问题标题】:Allow the user to input the list position of the word to RETURN to 2nd and 3rd element from the list允许用户输入单词的列表位置以返回列表中的第二个和第三个元素
【发布时间】:2020-01-04 00:28:40
【问题描述】:

我需要有人帮我编写代码,但不使用外部库 panda 导入异常计数器

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

2D 列表中出现超过 2 次的单词显示在数字列表中

例如:

1. Cat
2. Bat

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

c = 1, a = 2, t = 3

我是 Python 的初学者,所以不知道如何处理这个问题。

【问题讨论】:

    标签: python python-3.x duplicates nested-lists python-3.3


    【解决方案1】:

    您可以使用str.joinstr.formatenumerategenerator 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)
    

    【讨论】:

    • 我如何允许用户通过输入列表位置编号来选择一个单词,例如,如果他们输入 1,它将返回 Cat 及其在嵌套列表中的相应值,例如,'c',1, 2 ? :)
    • @gstar 我刚刚用这个问题的解决方案更新了我的答案。
    • @gstar 您必须在我的答案filtered = [p for p in word_counts if p[1] > 1] 的第一个代码中定义它。
    • 效果太棒了!唯一的是当我输入 1 时它只返回 cat。有没有办法让它从 LineList 返回所有其他元素,如 c、1 和 2,例如 ['Cat', 'c', 1, 2]
    • @gstar 如果用户输入1,你期望得到什么结果?
    【解决方案2】:

    使用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")
    

    【讨论】:

      【解决方案3】:

      你就在那里,只需检查嵌套列表中第二项的值是否大于 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
      

      【讨论】:

      • 因此,for 循环中 if 语句中的值 'i' 是原始 lineList 的索引。使用该索引号获取原始列表的信息。
      • 我在不同的评论中回答,因为问题的表述方式有所不同
      【解决方案4】:

      你稍微改变了描述,所以我重写了答案以更合适

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-22
        • 1970-01-01
        • 1970-01-01
        • 2013-11-26
        相关资源
        最近更新 更多