<<chunkid, echo = FALSE>>=
X = 2:10
summary(X)
@
目前打印出以下内容:
r = '{"available_sizes":[{"id":104682,"name":"40","preorder_only":false},{"id":104683,"name":"41","preorder_only":false},{"id":104684,"name":"42","preorder_only":false},{"id":104685,"name":"43","preorder_only":false},{"id":104687,"name":"45","preorder_only":false}]}'
data = json.loads(r)
for element in data:
for value in data['available_sizes']:
print(value['name'])
我如何将此数据用作字符串?以下是所需的输出。
40
41
42
43
45
答案 0 :(得分:1)
你最外面的循环是多余的,因为你只有一个密钥可以迭代。
对data
进行迭代,将您的数字附加到列表中,然后在结尾处调用str.join
以有效地将字符串连接在一起。
nums = []
for v in data['available_sizes']:
nums.append(str(v['name'])) # v['name'] if it is already string
print(f'Available sizes are {', '.join(nums)}')
您可以使用列表推导重写循环 -
num_str = ', '.join([v['name'] for v in data['available_sizes']])
print(f'Available sizes are {num_str}')
有关JSON数据遍历的入门知识,我建议您查看this answer。
答案 1 :(得分:0)
使用for-comprehension提取大小名称,然后使用str.join()
添加逗号分隔符:
import json
r = '{"available_sizes":[{"id":104682,"name":"40","preorder_only":false},{"id":104683,"name":"41","preorder_only":false},{"id":104684,"name":"42","preorder_only":false},{"id":104685,"name":"43","preorder_only":false},{"id":104687,"name":"45","preorder_only":false}]}'
data = json.loads(r)
# Extract the size names from the list of available sizes
size_names = [size_entry["name"] for size_entry in data["available_sizes"]]
# Join the sizes names as strings using a comma separator and print
sizes_string = ", ".join(size_names)
print("Available sizes are: " + sizes_string)
答案 2 :(得分:0)
做类似的事情这是你想要的输出
import json
r = '{"available_sizes":[{"id":104682,"name":"40","preorder_only":false},{"id":104683,"name":"41","preorder_only":false},{"id":104684,"name":"42","preorder_only":false},{"id":104685,"name":"43","preorder_only":false},{"id":104687,"name":"45","preorder_only":false}]}'
data = json.loads(r)
var = []
for element in data:
for value in data['available_sizes']:
var.append(value['name'])
print( 'Availble size are %s' %(', '.join(var)))