使用for和if循环将不同长度的元素组合到一个列表Python中

时间:2018-12-13 03:47:39

标签: python arrays python-3.x list

输入:

a = [{'layer': 'OVC', 'ceiling': '020', 'type': None}]
b = [{'layer': 'BKN', 'ceiling': '010', 'type': None}, {'layer': 'OVC', 'ceiling': '020', 'type': None}]
c = [{'layer': 'BKN', 'ceiling': '010', 'type': None}, {'layer': 'BKN', 'ceiling': '020', 'type': None},{'layer': 'OVC', 'ceiling': '030', 'type': None}]
d = [a,b,c] 

results1 = []
results2 = [] 

for i in range(0,len(d)):
 res1=[]
 res2=[]
 cloudstf = d[i]
 if not cloudstf:
  res1 = "-9999"
  res2 = "-9999"
  results1.append(res1)
  results2.append(res2)
 elif len(d[i])==1:
  res1 = d[i]["layer"]
  res2 = d[i]["ceiling"]
  results1.append([res1])
  results2.append([res2])
 elif len(d[i])>1:
  for k in range(0,len(d)):
   res1 = d[i][k]["layer"]
   res2 = d[i][k]["ceiling"]
   results1.append([res1])
   results2.append([res2])
 cloudtf = []

cloud_group_layer = results1
cloud_group_height = results2 
print(cloud_group_height)
print(cloud_group_layer)

而不是:

cloud_group_layer = [['OVC'], ['BKN'], ['OVC'], ['BKN'],['BKN'],['OVC']]
cloud_group_height = [['020'], ['010'], ['020'], ['010'],['020'],['030']]

我如何获得:

cloud_group_layer = [['OVC'], ['BKN','OVC'], ['BKN','BKN','OVC']]
cloud_group_height = [['020'], ['010','020'], ['010','020','030']]

其中图层和高度按how many分组。那里的代码只是语法上的一点混乱。或者由于高度而可能是Tuple

由于正在编制索引,因此在运行它时可能会出现此错误。

Traceback (most recent call last):
  File "main.py", line 22, in <module>
    res1 = d[i]["layer"]
TypeError: list indices must be integers or slices, not str 

2 个答案:

答案 0 :(得分:2)

您可以通过一些理解来做到这一点,例如:

代码:

cloud_group_layer = [[x['layer'] for x in data] for data in d]
cloud_group_height = [[x['ceiling'] for x in data] for data in d] 

测试代码:

a = [{'layer': 'OVC', 'ceiling': '020', 'type': None}]
b = [{'layer': 'BKN', 'ceiling': '010', 'type': None},
     {'layer': 'OVC', 'ceiling': '020', 'type': None}]
c = [{'layer': 'BKN', 'ceiling': '010', 'type': None},
     {'layer': 'BKN', 'ceiling': '020', 'type': None},
     {'layer': 'OVC', 'ceiling': '030', 'type': None}]

d = [a, b, c]

wanted_cloud_group_layer = [['OVC'], ['BKN', 'OVC'], ['BKN', 'BKN', 'OVC']]
wanted_cloud_group_height = [['020'], ['010', '020'], ['010', '020', '030']]

cloud_group_layer = [[x['layer'] for x in data] for data in d]
cloud_group_height = [[x['ceiling'] for x in data] for data in d]

assert wanted_cloud_group_layer == cloud_group_layer
assert wanted_cloud_group_height == cloud_group_height

答案 1 :(得分:0)

简单的解决方案可能是获取要附加的列表,而不是该列表的元素。假设您要附加['BKN','OVC'],然后不要附加['BKN']['OVC'],而是在获得它时附加整个列表。

希望这会有所帮助!