4

I have 2 lists dependent on each other like a person and where is he/she from. I want to make groups based on where they are from.

People = ["A","B","C","D","E","F"]
City = ["Bombay","Delhi","Pune","Pune","Bombay","Pune"]

Here, A is from Bombay, B is from Delhi, and like that. I want to group all people from Bombay in one group, Delhi in one group, and Pune in one group. Then I want to assign some task to each group, like people from Bombay will do task X, people from Delhi will do task Y, and people from Pune will do task Z. How can I do that in python?

A group is like a list. Example:

Bombay = ["A","E"]
Delhi = ["B"]
Pune = ["C","D","F"]
Axe319
  • 4,255
  • 3
  • 15
  • 31
Aakash Patel
  • 111
  • 7
  • What do you mean by "group"? What is your expected result? – Selcuk Aug 27 '20 at 13:28
  • group is like list example Bombay = ["A","E"] , Delhi = ["B"], Pune = ["C","D","F"] – Aakash Patel Aug 27 '20 at 13:28
  • @AakashPatel, If one of the answers below fixes your issue, you should accept it (click the check mark next to the appropriate answer). That does two things. It lets everyone know your issue has been resolved to your satisfaction, and it gives the person that helps you credit for the assist. [See here](http://meta.stackexchange.com/a/5235) for a full explanation. – sushanth Aug 28 '20 at 12:48

5 Answers5

4

Using itertools.groupby

from itertools import groupby

data = sorted(zip(People, City), key=lambda x: x[1])
for k, g in groupby(data, key=lambda x: x[1]):
    g = [x[0] for x in g]
    print(f'{k} = {g}')

Output:

Bombay = ['A', 'E']
Delhi = ['B']
Pune = ['C', 'D', 'F']
deadshot
  • 8,881
  • 4
  • 20
  • 39
  • i like your answer . can you please explain to me how this works ? – Gautamrk Aug 27 '20 at 14:55
  • 1
    you need to know how the `itertools.groupby` works this will help [What is itertools.groupby() used for?](https://stackoverflow.com/questions/41411492/what-is-itertools-groupby-used-for) – deadshot Aug 27 '20 at 14:59
  • Your answer is very helpful. But how to use new lists for further operation? – Aakash Patel Aug 27 '20 at 15:29
  • you can create dictionary. `res = {k: [x[0] for x in g] for k, g in groupby(data, key=lambda x: x[1])}` – deadshot Aug 27 '20 at 15:30
  • Still not able to use . I try to take output as print(Bombay[0]) and its say Bombay is not defined – Aakash Patel Aug 27 '20 at 15:45
  • 1
    you should use `print(res['Bombay'][0])` – deadshot Aug 27 '20 at 15:46
  • What if second list (city) is unknown and generated from input from the people of list People? How can I find out the elements from new list ? I created one temp list and append the k in that list and then tried print(res['temp[0]'][1]) but it is not working – Aakash Patel Aug 29 '20 at 16:46
  • In the example we have directly choose that A is from Bombay , B is from Delhi and so on.But if we have to take input from A that from which city he is and then to B and same to all people . This way city list is generate. clear? – Aakash Patel Aug 29 '20 at 17:20
  • do you mean if we give `A` as input you want to get `Bombay` as output? – deadshot Aug 29 '20 at 17:48
  • People = ["A","B","C","D","E","F"] City = [] for i in People: a = input("Hello!! {} Where are you from? : ".format(i)) City.append(a) print(City) # This is how city list will generate # This list will used for further work – Aakash Patel Aug 29 '20 at 17:57
  • copy the code in [pastebin](https://pastebin.com/) and share the link also add your issue in that file – deadshot Aug 29 '20 at 18:02
  • as per your example just use `res[a][0]` will give the first element of Bombay list. there is no need of temp it's list of keys in dictionary simply `temp = list(res.keys())` – deadshot Aug 29 '20 at 18:29
2

Here is another solution & storing in dict would be preferable over variable due to ease accessiblity.

result = {}

for c,p in zip(City, People):
    result.setdefault(c, []).append(p)

print(result)

{'Bombay': ['A', 'E'], 'Delhi': ['B'], 'Pune': ['C', 'D', 'F']}
sushanth
  • 8,275
  • 3
  • 17
  • 28
0

You can use a dictionary

Dict = dict()

People = ["A","B","C","D","E","F"]
City = ["Bombay","Delhi","Pune","Pune","Bombay","Pune"]

for i in range (len (City)):
    if City[i] in Dict:
        Dict[City[i]].append (People[i])
    else:
        Dict[City[i]] = [ People[i] ]

for city in Dict:
    print (city, end = ': ')
    for people in Dict[city]:
        print (people, end = ' ')

    print()

This prints:

Bombay: A E 
Delhi: B 
Pune: C D F

Similarly, create another Dictionary for the tasks and assign a task as a value to every key (city) from the city_of Dictionary

0

How about that?

People = ["A","B","C","D","E","F"]
City = ["Bombay","Delhi","Pune","Pune","Bombay","Pune"]


data={}
for P in People:
    for C in City:
        data[P]=C

def X():
    print('do stuff X')
def Y():
    print('do stuff Y')
def Z():
    print('do stuff Z')
def A():
    print('do stuff A')

tasks={
    "Bombay":X(),
    "Delhi":Y(),
    "Pune":Z(),
    "Pune":A(),
    "Bombay":A(),
    "Pune":A()
}


for item in data:
    tasks[data[item]]
Michał M
  • 61
  • 6
  • 1
    what if we have large number of cities? did you write `tasks` dictionary for all cities – deadshot Aug 27 '20 at 13:38
  • I've posted my solution for a given problem, not the ultimate answer. You can reuse function when a couple of cities do the same task or write a new one for when it's necessary. – Michał M Aug 27 '20 at 13:43
0

If you like one liners for maximum readability ;-) This list comprehension gets the unique cities and for every city name it gets the people in the zipped list that belong to this city:

people = ["A","B","C","D","E","F"]
cities = ["Bombay","Delhi","Pune","Pune","Bombay","Pune"]
    
result = [{city: [name[0]
 for name in list(zip(people, cities)) if name[1] == city]}
 for city in list(set(cities))]

print(result)

Output

[{'Pune': ['C', 'D', 'F']}, {'Bombay': ['A', 'E']}, {'Delhi': ['B']}]
andy meissner
  • 1,202
  • 5
  • 15