如何在python中显示嵌套字典中的多个值?



我的任务是创建一个嵌套字典,使用推导式在使用给定列表时显示结果。

例如,给定输入

given_list = ['iCLA', 'YGU', 'icla YGU', 'Hello World', 'Python']

代码应该产生:

{'iCLA': {'UPPER': ['C', 'L', 'A'], 'lower': ['i']},    
'YGU': {'UPPER': ['Y', 'G', 'U'], 'lower': []},    
'icla YGU': {'UPPER': ['Y', 'G', 'U'], 'lower': ['i', 'c', 'l', 'a']},    
'Hello World': {'UPPER': ['H', 'W'],    
'lower': ['e', 'l', 'l', 'o', 'o', 'r', 'l', 'd']},    
'Python': {'UPPER': ['P'], 'lower': ['y', 't', 'h', 'o', 'n']}}

嵌套部分使我感到困惑。我想我应该使用if条件来检查每个字母并将其放在列表中,但它对我不起作用。我如何编写代码?

可以做到。由于检查每个字符两次,它会损失一些效率,但系数损失没什么大不了的。

d = {
x: {"UPPER": [c for c in x if c.isupper()], "LOWER": [c for c in x if c.islower()]}
for x in given_list
}
print(d)

输出:

{'iCLA': {'UPPER': ['C', 'L', 'A'], 'LOWER': ['i']}, 'YGU': {'UPPER': ['Y', 'G', 'U'], 'LOWER': []}, 'icla YGU': {'UPPER': ['Y', 'G', 'U'], 'LOWER': ['i', 'c', 'l', 'a']}, 'Hello World': {'UPPER': ['H', 'W'], 'LOWER': ['e', 'l', 'l', 'o', 'o', 'r', 'l', 'd']}, 'Python': {'UPPER': ['P'], 'LOWER': ['y', 't', 'h', 'o', 'n']}}

有人可能认为您可以使用defaultdict来改善时间,但它实际上会减慢速度,即使字符检查每个字符只发生一次。然而,你最好的选择就是普通的循环结构。理解能力是很棒的,但也有一些情况是没有意义的。

在这里你可以看到时间:

from collections import defaultdict
from statistics import fmean
import timeit
given_list = ["iCLA", "YGU", "icla YGU", "Hello World", "Python"]

def with_comp(l):
return {
x: {
"UPPER": [c for c in x if c.isupper()],
"LOWER": [c for c in x if c.islower()],
}
for x in given_list
}

def with_defaultdict(l):
d = {}
for x in given_list:
d[x] = defaultdict(list)
for c in x:
d[x]["UPPER"].append(c) if c.isupper() else d[x]["lower"].append(c)
d[x] = dict(d[x])
return d
def plain(l):
d = {}
for x in given_list:
d[x] = {"UPPER": [], "lower": []}
for c in x:
d[x]["UPPER"].append(c) if c.isupper() else d[x]["lower"].append(c)
return d

time_with_comp = timeit.repeat(
stmt="d = with_comp(given_list)", setup="from __main__ import given_list, with_comp"
)
time_with_defaultdict = timeit.repeat(
stmt="d = with_defaultdict(given_list)",
setup="from __main__ import given_list, with_defaultdict",
)
time_plain = timeit.repeat(
stmt="d = plain(given_list)",
setup="from __main__ import given_list, plain",
)
print("with_comp: {:.2f}".format(fmean(time_with_comp)))
print("with_defaultdict: {:.2f}".format(fmean(time_with_defaultdict)))
print("plain: {:.2f}".format(fmean(time_plain)))

给出时间:

with_comp: 3.91
with_defaultdict: 4.85
plain: 3.50

我相信一定有更好的办法。

您可以使用O(n)解决方案,遍历每个单词上的所有字母并检查它们是低还是高,如下所示:

l = ['iCLA', 'YGU', 'icla YGU', 'Hello World', 'Python']
d = {}
for i in l:
up, low = [], []
for a in i:
if a.islower():
low.append(a)
else:
up.append(a)
d[i] = {"UPPER":up, "lower":low}
print(d)

输出:

{'iCLA': {'UPPER': ['C', 'L', 'A'], 'LOWER': ['i']}, 'YGU': {'UPPER': ['Y', 'G', 'U'], 'LOWER': []}, 'icla YGU': {'UPPER': [' ', 'Y', 'G', 'U'], 'LOWER': ['i', 'c', 'l', 'a']}, 'Hello World': {'UPPER': ['H', ' ', 'W'], 'LOWER': ['e', 'l', 'l', 'o', 'o', 'r', 'l', 'd']}, 'Python': {'UPPER': ['P'], 'LOWER': ['y', 't', 'h', 'o', 'n']}}

最新更新