小编Tom*_*aga的帖子

重写为字典理解

我想使用词典计算单词中所有字母的出现。到目前为止,我已经尝试过为dict添加for循环。

我想知道是否可以使用字典理解?

word = "aabcd"
occurrence = {}
for l in word.lower():
    if l in occurrence:
        occurrence[l] += 1
    else:
        occurrence[l] = 1
Run Code Online (Sandbox Code Playgroud)

python dictionary-comprehension

6
推荐指数
1
解决办法
179
查看次数

根据条件获取随机元素

我有两个列表:图像和相应的标签。我想通过给定的标签获得随机图像。我想过使用 numpy 数组来获取布尔数组,然后使用 list.index。问题是它返回第一次出现的索引。有任何想法吗?

python random numpy

1
推荐指数
1
解决办法
1977
查看次数

标签 统计

python ×2

dictionary-comprehension ×1

numpy ×1

random ×1