Search code examples
pythonpython-3.xduplicatesnested-listspython-3.3

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


I need someone to help me code this WITHOUT using external libraries 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]]

Words from 2D list that appear more than 2 times are displayed in a numerical list

Eg:

1. Cat
2. Bat

How can I allow the user to select a word by inputting the list position number? So for example if the user enters 1 it will return the second and third elements for Cat in the nested list:

c = 1, a = 2, t = 3

I am a beginner to Python so not sure how to approach this.


Solution

  • You can use 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)))
    

    Output:

    1. Cat
    2. Bat
    

    For a string in a specific position:

    n = int(input('position: '))   #   1-indexed
    
    print('{0}. {1}'.format(n, filtered[n - 1][0]))   #   0-indexed (hence, n - 1)