我想检查某个值是否在嵌套列表中。我有一个主列表,其中包含更多可以包含更多列表的列表等等。就像这样:
[['Hey', 1], 0, 0, 0, ['Heyyy', 1], [[['Hi', 1], ['Hiii', 1]],
['Hola', 1]], ['Hollaa', 2], ['Hallo', 1], 0, ['Hallooo', 1]]
现在我想检查一下是否有' Hiii'在其中一个列表中,如果这是True,我想更改列表的第二个值。
到目前为止,我尝试使用递归和生成器,但我实际上并不知道这是如何工作的。我不知道如何更改列表的第二个值。 ..
def search(nested_list):
for value in nested_list:
for subvalue in search(value):
yield subvalue
感谢您的帮助!
答案 0 :(得分:1)
假设:
LoL=[['Hey', 1], 0, 0, 0, ['Heyyy', 1], [[['Hi', 1], ['Hiii', 1]],
['Hola', 1]], ['Hollaa', 2], ['Hallo', 1], 0, ['Hallooo', 1]]
要检查,如果某个值位于列表列表中,请首先使用生成器来展平任意列表列表:
def flatten(it):
for x in it:
if (isinstance(x, collections.Iterable) and
not isinstance(x, str)):
yield from flatten(x)
else:
yield x
然后使用any
:
>>> any(x=="Hiii" for x in flatten(LoL))
True
>>> any(x=="BooHoo" for x in flatten(LoL))
False
更改列表清单:
def LoLedit(li, tgt, nv):
if isinstance(li, list):
if li[0]==tgt:
li[1]=nv
else:
for next_item in li:
LoLedit(next_item, tgt, nv)
return li
>>> LoLedit(LoL,"Hiii", "Changed")
[['Hey', 1], 0, 0, 0, ['Heyyy', 1], [[['Hi', 1], ['Hiii', 'Changed']], ['Hola', 1]], ['Hollaa', 2], ['Hallo', 1], 0, ['Hallooo', 1]]
答案 1 :(得分:1)
你走在正确的轨道上,但你不需要这里的生成器功能 - 简单的递归w / find&改变就足够了:
def search(source, find, new_value):
if isinstance(source, list): # no point searching in non-lists
if find in source:
source[1] = new_value
else:
for item in source:
search(item, find, new_value)
data = [['Hey', 1], 0, 0, 0, ['Heyyy', 1], [[['Hi', 1], ['Hiii', 1]], ['Hola', 1]],
['Hollaa', 2], ['Hallo', 1], 0, ['Hallooo', 1]]
search(data, "Hiii", 5)
print(data)
# prints:
# [['Hey', 1], 0, 0, 0, ['Heyyy', 1], [[['Hi', 1], ['Hiii', 5]], ['Hola', 1]],
# ['Hollaa', 2], ['Hallo', 1], 0, ['Hallooo', 1]]
这假设您在找到商品后不想进行更深入的搜索。
答案 2 :(得分:0)
一个非常基本的递归函数,用于查找和更新值。
{
"fld_status": "Online",
"fld_server_update": "Friday, May, 19, 2017 10:33:53 AM Central Daylight Time",
"fld_signalstr": "42%",
"fld_power": "23.98 Volts",
"fld_battery": "7.538 Volts",
"fld_temp": "72 Degrees F",
}
答案 3 :(得分:0)
另一种检查某个值是否在嵌套列表(列表列表)中的方法可以使用recursion
来完成:
# Flatten the list of lists into a simple list
def flatten_list(my_list, final=None):
if final is None:
final = []
for i in my_list:
if isinstance(i, list):
flatten_list(i, my_list)
else:
final.append(i)
return final
a = [['Hey', 1], 0, 0, 0, ['Heyyy', 1], [[['Hi', 1], ['Hiii', 1]],
['Hola', 1]], ['Hollaa', 2], ['Hallo', 1], 0, ['Hallooo', 1]]
check_element = lambda x, y: x in flatten_list(y)
# Some tests:
print(check_element('hey', a))
print(check_element('Hey', a))
print(check_element('Heyyy', a))
print(check_element('Hiii', a))
print(check_element(1, a))
print(check_element('foo', a))
输出:
False
True
True
True
True
False