使用键,删除所有具有类似值的键

2024-10-03 21:30:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我的目标是将水果的随机名称存储为水果名称。使用这个我想删除所有水果与相同的前三个字母在其价值。例如:

fruit_name = 'apple II'
dictionary = {'grape' : 'abc.asrtyui', 'apple' : 'xyz7.qwertyui',  'apple I' : 'xyz.rghhyui',  'grape II' : 'zxs2.qwertyui',  'apple II' : 'xyz.qwvnyyui', 'orange' : 'bnm1.qrthnrui'}

我的思维过程是:第1步:找到具有水果名称的键(在本例中为“apple II”)第2步:查看其值的前三个字母第3步:删除具有相同三个字母的所有键及其值。 因此,对于我上面的例子,在这个过程发生之后,字典将包含:

dictionary = {'grape' : 'abc.asrtyui', 'grape II' : 'zxs2.qwertyui', 'orange' : 'bnm1.qrthnrui'}

这是我的片段,不确定我是否在正确的方向,因为我完全困惑。另外,我想用标准库来实现这一点。提前谢谢!你知道吗

for k1, v1 in dictionary.items():
    for k2, v2 in dictionary.items():
        if k1 == k2:
            continue
        if v1[:3] == v2[:3]:

Tags: 名称appledictionary字母iiabcorangexyz
3条回答

你只需要把字典翻一次就行了。使用字典理解,我们可以表示“所有键/值,其中值不以键"apple II"的值的前三个字母开头”

fruit_name = 'apple II'
dictionary = {'grape' : 'abc.asrtyui', 'apple' : 'xyz7.qwertyui',  'apple I' : 'xyz.rghhyui',  'grape II' : 'zxs2.qwertyui',  'apple II' : 'xyz.qwvnyyui', 'orange' : 'bnm1.qrthnrui'}

{k: v for k, v in dictionary.items() if not v.startswith(dictionary[fruit_name][:3])}
# {'grape': 'abc.asrtyui', 'grape II': 'zxs2.qwertyui', 'orange': 'bnm1.qrthnrui'}
while True:
    if fruit_name == dictionary[fruit_name]:
        del dictionary[fruit_name]

这个怎么了?你知道吗

fruit_name = 'apple II'
dictionary = {'grape' : 'abc.asrtyui', 'apple' : 'xyz7.qwertyui',  'apple I' : 'xyz.rghhyui',  'grape II' : 'zxs2.qwertyui',  'apple II' : 'xyz.qwvnyyui', 'orange' : 'bnm1.qrthnrui'}
val = fruit_name[:3]
delete_vals = []
for i in dictionary.keys():
    if i[:3] == val:
        delete_vals.append(i)
for i in delete_vals:
    del dictionary[i]

那么,这是怎么回事?首先,我们使用字符串切片将变量val定义为fruit_name的前三个字母。然后,我们检查字典的键,发现所有这些都是键匹配的前三个字符val,并将它们附加到“delete list”(不能在循环中删除它们,因为这样您就可以修改正在迭代的内容)。然后在一个单独的for循环中,我们遍历delete列表并删除字典中相应的值。你知道吗

不一定是最短的方法,但最简单的眼睛。你知道吗

相关问题 更多 >