举个例子:
"something": {
"random": 0,
"bag": {
"papers": 0,
"pencils": 0
},
"PAINT": {
"COLORS": [
"A WHITE",
"B MAPLE",
"B LOTUS",
"A OLIVE"
],
"CANS": [
"SOMETHING"
]
}
忽略一切,专注于油漆字典中的颜色列表。。。我想打印所有之前有颜色A的颜色,作为一个代码。换句话说,我想打印";白色";以及";橄榄油";。当我这样做时会发生以下情况:
with open("somethings.json", "r") as f:
data = json.load(f)
print(data["something"]["PAINT"]["COLORS"])
这是输出:
["A WHITE", "B MAPLE", "B LOTUS", "A OLIVE"]
但就像我说的,我不想那样。。。我只想印A色。。。我也不想要这个:
["A WHITE", "A OLIVE"]
我真正想要的输出(非常具体(是:
OLIVE
WHITE
使用换行符(可选:按字母顺序为AND(,这就是我想要的输出。那么我如何打印这个输出呢?是否可以不使用任何for循环?这是一个非常具体的问题,希望得到一些帮助。谢谢-
试试这个代码:
with open("somethings.json", "r") as f:
data = json.load(f)
a_colors = [color for color in data["something"]["PAINT"]["COLORS"] if color.startswith("A ")]
colors = [a_color.replace("A ", "") for a_color in a_colors]
print(colors)
它的工作原理
- 打开并加载JSON数据
- 使用列表理解仅筛选以
"A "
开头的条目。字符串的.startswith()
方法返回布尔值,如果字符串的前几个字符实际上是作为参数传递的字符,则返回True
,否则返回False
- 对于步骤2中创建的列表中的每个字符串,使用另一个列表理解来获得不带
"A "
的字符串。用空字符串替换"A "
,这是一种使用.replace()
方法删除部分字符串的方法
也可以使用for循环在没有列表理解的情况下完成
请参阅以下代码:with open("somethings.json", "r") as f:
data = json.load(f)
a_colors = []
for color in data["something"]["PAINT"]["COLORS"]:
if color.startswith("A "):
color_without_a = color.replace("A ", "")
a_colors.append(color_without_a)
print(a_colors)
此解决方案使用for循环而不是列表理解,但在其他方面是相同的。(如果您感到困惑,请参阅下面的解决方案,该解决方案是列表理解解决方案的精确副本,但使用for循环实现(。
如果你感兴趣,这里有一个更长的解决方案,更类似于列表理解,用于循环:
with open("somethings.json", "r") as f:
data = json.load(f)
a_colors = []
for color in data["something"]["PAINT"]["COLORS"]:
if color.startswith("A "):
a_colors.append(color)
colors = []
for a_color in a_colors:
colors.append(a_color.replace("A ", ""))
print(colors)
要按字母顺序排序,请使用sorted()
函数,对于列表理解解决方案是这样,对于循环解决方案是第二个:
sorted_list = sorted(colors)
print(sorted_list)
对于第一个针对环路的解决方案:
sorted_list = sorted(a_colors)
print(sorted_list)
推荐阅读
- Python数据结构文档
- 实践中的列表理解示例
- 初学者列表理解教程
- Python中的筛选列表
其他有用的资源
- 列表切片
- 排序列表
I强烈建议也观看此视频:
- Python初学者教程7:循环和迭代-for/While循环
好吧,你不能真的不使用for
-循环,你需要迭代你的COLORS
数组中的所有元素。所以,你想做的是:
- 遍历所有元素
- 检查每个元素的第一个字符(例如
A WHITE
(是否为所需字符(例如,A
( - 直接打印输出或将其存储在不带
A
的列表中(注意空格(
所以:
with open("somethings.json", "r") as f:
data = json.load(f)
colors = data["something"]["PAINT"]["COLORS"]
best_colors = []
for color in colors:
if color[0] == "A": # or any character you want; CASE SENSITIVE!
best_colors.append(color[2:]) # this adds the color without the A and the space to the list
# Optionally: Sort alphabetically
sorted_colors = sorted(best_colors)
帮助您更好地理解代码的其他资源:
- 列表切片
- 排序列表
基于Unix Doughnut的答案:
# Read JSON File
with open("file_name.json", "r") as f:
data = json.load(f)
# Sort the selected elements starting with A without the leading A
colors = sorted([color.replace("A ", "") for color in data["something"]["PAINT"]["COLORS"] if color.startswith("A ")])
# Print list elements separated by line break ( without for loop )
print(*colors, sep='n')`