Home>

The list is as follows.

list = [(1,'Tokyo', 4), (3,'Tokyo', 6), (2,'Osaka', 9), (7,'Kobe', 10), (4,'Kobe', 8)]

They are sorted by group as list.sort (key = itemgetter (1)).

In this list

Number of cities(Tokyo: 2, Osaka: 1, Kobe: 2)
How to get the city name(For example, how to find out that there are Tokyo, Osaka, Kobe groups in this list)

I want to know.

I will add the missing information, so please leave a comment.

  • Answer # 1

    As an example, it will be easier if you handle it by putting it back in the dictionary of "city = number".
    Type (dictionary)-Python3

    list = [(1,'Tokyo', 4), (3,'Tokyo', 6), (2,'Osaka', 9), (7,'Kobe', 10), (4,'Kobe', 8)]
    #City name: Dictionary of numbers
    cities = {}
    for tv in list:
        k = tv [1]
        if k in cities:
            cities [k] + = 1
        else: else:
            cities [k] = 1
    #Cities list can be obtained with cities.keys ().
    #City
    print ('names = {}'. format (','. join (cities.keys ())))
    #Number of cities
    for name in cities.keys ():
        print ('{} = {}'. format (name, cities [name]))

    This is an execution example.

    $python3 --version
    Python 3.6.9
    $python3 t1.py
    names = Tokyo, Osaka, Kobe
    Tokyo = 2
    Osaka = 1
    Kobe = 2

Trends