Max Powers
Max Powers

Reputation: 1179

for loop with dynamic if statement in python

I have these two list group_name and group_ids_list im looping these two list and I want to do an if condition based on the group id of this list. I want to know if there is a way to do this if groupId == 0: dynamically because this current example wont scale very well if I keep adding more groups and so on.

group_name = ['a','a','b','c', 'a', 'd']
group_ids_list = [0,0,1,2,0,3]
for groupName, groupId in itertools.zip_longest(group_name, group_ids_list):
    if groupId == 0:
        print('found group 0 name is {}'.format(groupName))
    elif groupId == 1:
        print('found group 1 name is {}'.format(groupName))
    elif groupId == 2:
        print('found group 2 name is {}'.format(groupName))

Upvotes: 0

Views: 73

Answers (1)

mohammed wazeem
mohammed wazeem

Reputation: 1328

If you want to just print the group id and name. You can use string formatting to achieve this.

group_names = ['a','a','b','c', 'a', 'd']
group_ids = [0, 0, 1, 2, 0, 3]
for group_name, group_id in zip(group_names, group_ids):
    print('found group {} with name {}'.format(group_id, group_name))

Upvotes: 1

Related Questions