简体   繁体   English

如何排除字典中的特定元素?

[英]How to exclude a specific element in a dictionary?

I want to work with a random name from my_dict , except for the name "name300000.&**" , I want to skip it and pass to another name when choice(my_dict.values()) = "name300000.&**".我想使用 my_dict 中的随机名称,除了名称 "name300000.&**" ,我想跳过它并在 selection(my_dict.values()) = "name300000.&**" 时跳过它并传递给另一个名称. So I did the following, but I am looking for a better solution ?所以我做了以下,但我正在寻找更好的解决方案?

from random import choice
my_dict = {1: "name1", 2: "name2", 3:"name300000.&**", 4:"name4"}
if "name3" in choice(my_dict.values()):
    pass
name = choice(my_dict.values())

你可以简单地做

name = choice(tuple(set(my_dict.values()) - {"name300000.&**"}))

This is a possible solution:这是一个可能的解决方案:

from random import choice
my_dict = {1: "name1", 2: "name2", 3:"name300000.&**", 4:"name4"}

name = choice(list(my_dict.values()))
while name == "name300000.&**":
    name = choice(my_dict.values())

print(name)

Or, another possible solution is:或者,另一种可能的解决方案是:

from random import choice
my_dict = {1: "name1", 2: "name2", 3:"name300000.&**", 4:"name4"}


while True:
    name = choice(list(my_dict.values()))
    if name != "name300000.&**":
        break

print(name)

The point is that you have to emulate a do while loop to correctly solve this problem, and in python, since it is not natively present, you can write in these ways.关键是你必须模拟一个 do while 循环来正确解决这个问题,而在 python 中,由于它本身不存在,你可以用这些方式编写。

You can simply use set difference function to remove unwanted values:您可以简单地使用设置差异函数来删除不需要的值:

from random import choice
my_dict = {1: "name1", 2: "name2", 3:"name300000.&**", 4:"name4"}
name = choice(list(set(my_dict.values()).difference({"name300000.&**"})))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM