I'm trying to find and output a specific value in a list. I've tried several methods, but no one give me the right result. Please, give me some advice, how can I resolve this problem or what am i doing wrong?
Input:
list1 = [(2555, '1.1.1', None, 'eh46172jdd', True, (4444, 4, 13), ['1a', '2b', '3c', '4d'], 4788, '1.1.0', 'zf1a122tyo', None, True, 6, 'ZY375b9', None, 2, 0)]
value = 'eh46172jdd'
What I tried:
1)
compare = [i for i in list1 if value in list1 ]
print(compare)
if (len(compare) > 0):
print ("find")
else:
print ("not find")
if (value in list1):
print ("find")
else:
print ("not find")
if (list1.count(value) > 0):
print ("find")
else:
print ("not find")
Output all times: not find
CodePudding user response:
You need to run trought the array first:
for item in list1:
print(item)
this will print every single item inside that list.
To look for a specific value you need to compare your value
to every single list item as follows:
for item in list1:
if (value in item):
print("find")
else:
print("not find")
Also, that list only has 1 value wich is:
(2555, '1.1.1', None, 'eh46172jdd', True, (4444, 4, 13), ['1a', '2b', '3c', '4d'], 4788, '1.1.0', 'zf1a122tyo', None, True, 6, 'ZY375b9', None, 2, 0)
If you want to make this a list with multiple items remove the () at the end and beggining
CodePudding user response:
What you need to do is
list1 = [(2555, '1.1.1', None, 'eh46172jdd', True, (4444, 4, 13), ['1a', '2b', '3c', '4d'], 4788, '1.1.0', 'zf1a122tyo', None, True, 6, 'ZY375b9', None, 2, 0)]
value = 'eh46172jdd'
compare = [i for i in list1 if value in i]
print(compare)
if (len(compare) > 0):
print ("find")
else:
print ("not find")
CodePudding user response:
Your list contains a tuple, which contains other nested elements. If you want to just search the tuple, you can do that directly:
'found' if value in list1[0] else 'not found'
If you want to something more general, you'll need an appropriately tailored function that can navigate the nested structures. For example, you can make something that can navigate lists, tuples, and sets like this:
def search(container, key):
if key in container:
return True
for item in container:
if isinstance(item, (list, tuple, set)) and search(item, key):
return True
return False
print('found' if search(list1, value) else 'not found')
CodePudding user response:
You created a list containing a tuple. Maybe you just wanted to create a list:
list1 = [2555, '1.1.1', None, 'eh46172jdd', True, (4444, 4, 13), ['1a', '2b', '3c', '4d'], 4788, '1.1.0', 'zf1a122tyo', None, True, 6, 'ZY375b9', None, 2, 0]
All your methods should work in this case.