How can I access the strings of 'X'
list = [['X','Y','Z'], ['X','Z','Y']]
For example I want to define a function to return True
if list[1]
of both list is equal to 'X'
Padraic Cunningham
181k30 gold badges264 silver badges327 bronze badges
asked Aug 26, 2015 at 9:39
user5267837user5267837
2 Answers 2
You can use all
to see if all ith elements in each sublist are the same:
def is_equal(l, i):
first = l[0][i]
return all(sub[i] == first for sub in l)
You might want to catch an IndexError in case i
is outside the bounds of and sublist:
def is_equal(l, i):
try:
first = l[0][i]
return all(sub[i] == first for sub in l)
except IndexError:
return False
If you want to explicitly pass a value to check:
def is_equal(l, i, x):
try:
return all(sub[i] == x for sub in l)
except IndexError:
return False
answered Aug 26, 2015 at 9:42
-
@Eric, no worries, you may want to let a user know if
i
was outside the bounds of any sublistPadraic Cunningham– Padraic Cunningham2015年08月26日 09:49:43 +00:00Commented Aug 26, 2015 at 9:49
def check_list(list):
for a in list:
if a == "X"
return True
return False
def check_list_list(list):
try:
return check_list(list[1])
except IndexError:
return False
answered Aug 26, 2015 at 9:48
lang-py
all('X' in x[0] for x in your_list)
all('X' in x[0] for x in your_list)
is wrong,"X" in "FOO X"
is True