我试图在我的 Perl 目录中循环一些文件。假设我当前的目录包含:song0.txt、song1.txt、song2.txt、song3.txt、song4.txt。
我提供“song?.txt”作为我程序的参数。
当我做:
foreach $file (glob "$ARGV[0]") {
printf "$file\n";
}
Run Code Online (Sandbox Code Playgroud)
它在打印“song0.txt”后停止。
但是,如果我将“$ARGV[0]”替换为“song?.txt”,它会按预期打印出所有 5 个。为什么 Perl glob 不能处理变量,我该怎么做才能解决这个问题?
我有一个字典列表,其中每个字典都有键“ shape”和“ colour”。例如:
info = [
{'shape': 'pentagon', 'colour': 'red'},
{'shape': 'rectangle', 'colour': 'white'},
# etc etc
]
Run Code Online (Sandbox Code Playgroud)
我需要找到最常见的形状/颜色组合。我决定通过在列表中找到最常见的字典来做到这一点。我将方法缩减为:
frequency = defaultdict(int)
for i in info:
hashed = json.dumps(i) # Get dictionary, turn into string to store as key in frequency dict
frequency[hashed] += 1
most_common = max(frequency, key = frequency.get) # Get most common key and unhash it back into dict
print(json.loads(most_common))
Run Code Online (Sandbox Code Playgroud)
我是python的新手,我总是总会发现大约1-2行的函数,这些函数最终会做我想做的事情。我想知道在这种情况下是否存在更快的方法?也许这可以最终帮助另一个初学者,因为经过数年的搜索后我找不到任何东西。