Python - 根据字符串中指定的重复字符查找单词

发布于 2024-12-12 09:21:12 字数 308 浏览 0 评论 0原文

假设我有一个单词列表: 辞职 树脂 重染 抵抗 我

我还有一个字符串“.10.10”,

需要遍历列表并找到在字符串中有数字的相同位置有重复字符的单词。

例如,字符串“.10.10”会找到单词“redyed”,因为有 1 的地方有 e,有 0 的地方有 d。

另一个字符串“.00.0”。会找到单词“reeded”,因为该位置有 e。

到目前为止,我在 python 中的尝试并不值得打印。目前,我查看字符串,将所有 0 添加到数组中,将 1 添加到数组中,然后尝试查找数组位置中的重复字符。但它非常笨拙并且无法正常工作。

Let's say I have a list of words:
resign
resins
redyed
resist
reeded

I also have a string ".10.10"

I need to iterate through the list and find the words where there are repeated characters in the same locations where there are numbers in the string.

For instance, the string ".10.10" would find the word 'redyed' since there are e's where there are 1's and there are d's where there are 0's.

Another string ".00.0." would find the word 'reeded' as there are e's in that position.

My attempts in python so far are not really worth printing. At the moment I look through the string, add all 0s to an array and the 1s to an array then try to find repeated characters in the array positions. But it's terribly clumsy and doesn't work properly.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

因为看清所以看轻 2024-12-19 09:21:12
def matches(s, pattern):
    d = {}
    return all(cp == "." or d.setdefault(cp, cs) == cs
               for cs, cp in zip(s, pattern))

a = ["resign", "resins", "redyed", "resist", "reeded"]
print [s for s in a if matches(s, ".01.01")]
print [s for s in a if matches(s, ".00.0.")]

印刷

['redyed']
['reeded']
def matches(s, pattern):
    d = {}
    return all(cp == "." or d.setdefault(cp, cs) == cs
               for cs, cp in zip(s, pattern))

a = ["resign", "resins", "redyed", "resist", "reeded"]
print [s for s in a if matches(s, ".01.01")]
print [s for s in a if matches(s, ".00.0.")]

prints

['redyed']
['reeded']
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文