【问题标题】:How to search for all the characters from a string in all Dictionary.Values()如何从所有 Dictionary.Values() 中的字符串中搜索所有字符
【发布时间】:2018-05-01 18:29:53
【问题描述】:

首先,我知道我在下面列出了许多类似的帖子,但是,据我所知,没有人回答我面临的问题,因为我发现的所有内容都在询问如何搜索字符串在 'dict.values()' 中,而不是搜索字符串中的每个字符,并检查它是否在 'dict.values()' 中,以及是否在字符串中找到出现在 'dict 的字符中的任何字符.values()' 它将返回哪个和多少。

没有回答问题但可能对某些人有用的类似帖子的链接:

How to search if dictionary value contains certain string with Python

Find dictionary items whose key matches a substring

How can I check if the characters in a string are in a dictionary of values?

How to search if dictionary value contains certain string with Python

这是我目前所拥有的,但似乎根本不起作用......

characters = {'small':'abcdefghijklmnopqrstuvwxyz',
              'big':'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 
              'nums':'0123456789',
              'special':"!#$%&()*+,-./:;<=>?@[\]^_{|}~",}

password = 'aAb'

def count(pass_word,char_set):

    num_of_char = 0
    char_list = []

    for char in pass_word:
        if i in char_set.values():
            num_of_char +=1
            char_list += i

    return char_list, num_of_char


#Print result

print(count(password,characters))

输出应该类似于:

'a','A','b'
3

希望您理解我的意思,如果有任何不清楚的地方,请发表评论,以便我改进。

【问题讨论】:

  • 很抱歉问,你是什么意思模块明智,因为我是新手,从来没有遇到过这个短语
  • 别担心他,你需要做的就是提供相关的标签,你做了。如果他不想看帖子,就去他妈的。
  • 添加一行打印 char_set.values() ,你会看到出了什么问题。

标签: python string python-3.x dictionary


【解决方案1】:
def count(password, char_dict):
    sanitized_pass = [char for char in password if any(char in v for v in char_dict.values())]
    return sanitized_pass, len(sanitized_pass)

这是一种方法。另一个是构建所有可接受的 c 的set 字符并使用密码将其传递给函数

from itertools import chain


char_set = set(chain.from_iterable(characters.values()))

def count(password, chars):
    sanitized_pass = [char for char in password if char in char_set]
    return sanitized_pass, len(sanitized_pass)

【讨论】:

  • 嘿,我只是想知道从哪个 'dict.key()' 中找到每个字符的代码是什么?
  • @Ivan 我不确定我是否理解。您的意思是要确定我们使用哪个字母来替换某个字符?如果有重复项,后面的条目将覆盖前面的条目,因此将使用更接近 alphabets 可迭代结尾的字母
猜你喜欢
  • 2011-03-22
  • 1970-01-01
  • 1970-01-01
  • 2021-12-15
  • 1970-01-01
  • 2016-05-06
  • 2017-07-04
  • 1970-01-01
  • 2015-10-10
相关资源
最近更新 更多