【问题标题】:Python with Json, If StatementPython 与 Json,If 语句
【发布时间】:2019-12-06 17:04:27
【问题描述】:

我有下面的 json 代码,我有一个列表

我想做一个for循环或if语句

if label in selected_size:
  fsize = id

selected_size[]

在选定的大小:

[7, 7.5, 4, 4.5]

在 json 中:

removed
print(json_data)
for size in json_data:
    if ['label'] in select_size:
        fsize = ['id']
print(fsize)

我不知道该怎么做。

【问题讨论】:

  • 你想从这个列表中得到什么?
  • size['label'], size['id']...!?此外,size['label'] 是一个字符串,而 selected_size 是数字。您需要转换其中一个或另一个才能正常工作。
  • @deceze 你的评论帮助我做出回答。

标签: python json


【解决方案1】:

你需要先访问list,然后再访问dict,例如:

json_data = [{'id': '91', 'label': '10.5', 'price': '0', 'oldPrice': '0', 'products': ['81278']}, {'id': '150', 'label': '9.5', 'price': '0', 'oldPrice': '0', 'products': ['81276']}, {'id': '28', 'label': '4', 'price': '0', 'oldPrice': '0', 'products': ['81270']}, {'id': '29', 'label': '5', 'price': '0', 'oldPrice': '0', 'products': ['81271']}, {'id': '22', 'label': '8', 'price': '0', 'oldPrice': '0', 'products': ['81274']}, {'id': '23', 'label': '9', 'price': '0', 'oldPrice': '0', 'products': ['81275']}, {'id': '24', 'label': '10', 'price': '0', 'oldPrice': '0', 'products': ['81277']}, {'id': '25', 'label': '11', 'price': '0', 'oldPrice': '0', 'products': ['81279']}, {'id': '26', 'label': '12', 'price': '0', 'oldPrice': '0', 'products': ['81280']}]
fsize = []
select_size = [7, 7.5, 4, 4.5]
[float(i) for i in select_size] #All select_size values to float value
for size in json_data:
    if float(size['label']) in select_size: #For compare it i need float(size['label']) for convert to float.
        fsize.append(size['id']) #Add to list

print(fsize) #Print all list, i get only 28

【讨论】:

  • 非常感谢,这正是我想要的。
猜你喜欢
  • 2015-12-14
  • 1970-01-01
  • 1970-01-01
  • 2022-12-05
  • 1970-01-01
  • 2017-08-29
  • 1970-01-01
  • 2018-08-05
  • 2015-06-20
相关资源
最近更新 更多