문제

I have a list of tuples:

MyList = [('name1', 'surname1', 'age1'), ('name2', 'surname2', 'age2'), ...]

I would like to make a check "if 'name2' in MyList, something like:

if 'name2' in MyList[?][0]: 
    print "do something"

If I would write if 'name2' in MyList[0] I would be accessing the element ('name1', 'surname1', 'age1') while what I meant is to access the element at position 0 of every tuple in the list. I guess there is a syntaxis to do that but I'm a newbie and cannot find it online myself, can anyone help me with this?

도움이 되었습니까?

해결책

You can use any function and a generator function, like this

if any("name2" in name for name, surname, age in my_list):
    # do something

Here all the elements of tuples are unpacked to name, surname, age while iterating. So, we can simply check if name2 is in name. This is the same as writing

if any("name2" in current_item[0] for current_item in my_list):

This will be efficient, as it yields True immediately after there is a match, rest of the items need not be checked.

If you are looking for a way to compare two strings, you should be using == operator, like this

if any("name2" == name for name, surname, age in my_list):
# do something

다른 팁

Sounds that you could benefit from using dictionaries:

my_dict = dict( (x[0],(x[1],x[2])) for x in MyList)

Then you can check for existence 'names2' in my_dict and also access directly the data my_dict['names2']

I am not sure if this is the most efficient method, but you could use this.

>>>MyList = [('name1', 'surname1', 'age1'), ('name2', 'surname2', 'age2'), ...]
>>> if 'name2' in zip(*MyList)[0]:
              #do something. 

The point is it creates a transpose of the original list. Caveat: All tuples have to be of same length to avoid data loss.

EDIT: Official docs for zip.

Official docs for * operator used in unpacking argument lists.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top