Python list of list retrieve data
Having a such list of list:
data = [['a','开发者_StackOverflow中文版x'], ['b','q'], ['c','z']]
search = 'c'
any(e[0] == search for e in data)
This returns boolean value but what if I want to retrieve the first appearing other pair of seach variable (in other words I want to retrieve 'x' when I search 'a' )?
You can use dict(data)['c']
to obtain the second value in the pair.
dict(data)
creates a dictionary from your pairs. Note that this will return a single result, and it's not guaranteed to return the first match. But if you perform many searches and you know that you don't have duplicates, it would be faster to use a dictionary.
Otherwise, use zeekay's answer.
You could use a list comprehension instead:
>>> search = 'a'
>>> [item[1] for item in data if item[0] == search]
<<< ['x']
The right-hand part of the expression filters results so that only items where the first element equals your search value are returned.
If you only need the first occurrence, then don't create an intermediate list using a list comprehension as this will search the whole list.
Instead, use next()
with a generator expression, which will return as soon as it finds a match:
>>> next(snd for fst, snd in data if fst == 'a')
'x'
>>> data = [['a','x'], ['b','q'], ['c','z']]
>>> search = 'c'
>>> print [e[1] for e in data if e[0] == search]
['z']
Really, though, you want a dictionary:
>>> datadict = {'a':'x', 'b':'q', 'c':'z'}
>>> search = 'c'
>>> print datadict[search]
z
data = [['a','x'], ['b','q'], ['c','z']]
search = 'c'
for inner_list in data:
if search in inner_list:
print(inner_list[1])
精彩评论