[英]iterating over list with different elements
I have three types of element: a dict, a list with one dict, and a list with multiple dicts. 我有三种类型的元素:一个dict,一个包含一个dict的列表和一个包含多个dict的列表。
a = {"foo":1}
b = [{"foo":2}]
c = [{"foo":3}, {"foo":4}]
list = [a, b, c]
I want to be print all four values. 我想打印所有四个值。 The only ways I came up with were either checking
type()
of each element of list
, or using try
and except
, like so: 我想到的唯一方法是检查
list
的每个元素的type()
,或使用try
和except
,例如:
for i in list:
try: # i is a dict
print(i["foo"])
except: # i a list
for e in i:
print(e["foo"])
Is there any better way to do it? 有什么更好的方法吗?
You can use isinstance
您可以使用
isinstance
Ex: 例如:
a = {"foo":1}
b = [{"foo":2}]
c = [{"foo":3}, {"foo":4}]
l = [a, b, c]
for i in l:
if isinstance(i, dict): #Check if dict object
print(i["foo"])
elif isinstance(i, list): #Check if list object
for j in i:
print(j["foo"])
Output: 输出:
1
2
3
4
You can check the datatype explicitly: 您可以显式检查数据类型:
mylist = [a, b, c]
for i in mylist:
if isinstance(i,dict):
print(i["foo"])
elif isinstance(i,list):
for e in i:
print(e["foo"])
But this won't work if you call your variable list
. 但是如果你调用变量
list
话这是行不通的 。 This snippet illustrates why you should not do that. 此代码段说明了为什么您不应该这样做。
You can use a recursive generator with your try
/ except
idea: 您可以将递归生成器与
try
/ except
想法一起使用:
a = {"foo":1}
b = [{"foo":2}]
c = [{"foo":3}, {"foo":4}]
L = [a, b, c]
def get_values(x):
for i in x:
try:
yield i['foo']
except TypeError:
yield from get_values(i)
res = list(get_values(L)) # [1, 2, 3, 4]
Alternatively, using `isinstance: 或者,使用`isinstance:
def get_values(x):
for i in x:
if isinstance(i, dict):
yield i['foo']
else:
yield from get_values(i)
Note you should never name variables after built-ins, eg use list_
or L
instead of list
. 注意, 永远不要在内置变量之后命名变量,例如,使用
list_
或L
代替list
。
If you want to do it for more nested elements like a list in a dict in a list you can create a function for every possible datatype. 如果要对更多嵌套元素(例如列表中的dict中的列表)执行此操作,则可以为每种可能的数据类型创建一个函数。
class Printer():
def print_element(self, element):
if isinstance(element, dict):
self._print_dict(element)
elif isinstance(element, list):
self._print_list(element)
else:
print(element)
def _print_dict(self, element):
for key,value in element.items():
self.print_element(value)
def _print_list(self, element):
for value in element:
self.print_element(value)
a = {"foo":1}
b = [{"foo":2}]
c = [{"foo":3}, {"foo":4}, [1, {"foo":[9,8,7,6]}]]
Printer().print_element(c)
Output: 输出:
3
4
1
9
8
7
6
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.