我有以下格式的字典:
folders = {'Master folder': ['Training'], 'Child folder': ['Training videos', 'Training documents', 'Training workouts', 'Training practicals']}
我希望计算以下期望值,
count_of_masterfolder = 1
count_of_childfolder = 4
到目前为止,我做到了,
co_master = folders.items['Master folder']
co_child = folders.items['Child folder']
print(co_master, co_child)
出现此错误:
co = folders.items['Master folder']
TypeError: 'builtin_function_or_method' object is not subscriptable
我该怎么办?
答案 0 :(得分:1)
您是要让 path = sys.argv[1]
all = glob.glob(path + "/x.txt")
print all
Output:
['/home/x1/sale/x.txt']
等作为程序的输出,还是要将计数分配给变量?
在前一种情况下,您可以使用以下内容:
count_of_masterfolder = 1
在后一种情况下,以下将适用于您的特定情况:
for key, value in folder.items():
print ("count of", key, "=", len(value))
答案 1 :(得分:0)
您可以尝试 dict 理解:
{k: len(v) for k,v in folders.items()}
完整示例:
folders = {'Master folder': ['Training'], 'Child folder': [
'Training videos', 'Training documents', 'Training workouts', 'Training practicals']}
print({k: len(v) for k,v in folders.items()})
# {'Master folder': 1, 'Child folder': 4}
答案 2 :(得分:0)
folders = {'Master folder': ['Training'], 'Child folder': ['Training videos', 'Training documents', 'Training workouts', 'Training practicals']}
for key in list(folders.keys()):
print(key, len(folders[key]))
>>>> Master folder 1
>>>>Child folder 4
EDIT: (to store outputs in list)
''''
mylist = []
for key in list(folders.keys()):
print(key, len(folders[key]))
mylist.extend(len(folders[key]))
答案 3 :(得分:0)
为什么只需要使用len
函数就可以解决问题
count_of_masterfolder = len(folders['Master folder'])
count_of_childfolder = len(folders['Child folder'])