python-如何检查数组是否包含值,但串联

发布于 2025-02-07 10:07:16 字数 396 浏览 3 评论 0原文

我想检查数组是否包含值,但在串联示例中:

word = 'hello'
def splite(word):
    return list(word)
for i in range(len(word)):
    letter = splite(word[i])
    if 'e' in letter:
        print('e')
    if 'h' in letter:
        print('h')

输出是

eh

,我希望输出到

he

我知道的,因为在脚本中,字母“ e”检测到了,但我希望首先检测字母“ H”,因为在单词中“你好” H是第一个,我该怎么做?

I want to check if the array contains value but in series example:

word = 'hello'
def splite(word):
    return list(word)
for i in range(len(word)):
    letter = splite(word[i])
    if 'e' in letter:
        print('e')
    if 'h' in letter:
        print('h')

the output is

eh

and I want the output to

he

I know because in the script the letter 'e' detect first but I want the letter 'h' detect first because in the word 'hello' h is first, how can I do that?

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

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

发布评论

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

评论(2

千寻… 2025-02-14 10:07:16

由于字符串是字符列表,因此您无需将其拆分。您可以像“正常”列表一样迭代它:

word = 'hello'
for i in range(len(word)):
    letter = word[i]
    if 'h' == letter:
        print('h')
    if 'e' === letter:
        print('e')

您的代码如何产生eh?测试代码时,它总是打印He。该代码的实际目标是什么?

Since a string is a list of characters, you dont need to split it. You can just iterate over it like it would be a 'normal' list:

word = 'hello'
for i in range(len(word)):
    letter = word[i]
    if 'h' == letter:
        print('h')
    if 'e' === letter:
        print('e')

How did your code produce eh? When testing your code it always printed he. What is the actual goal of this code snipped?

痴情 2025-02-14 10:07:16

从您的问题标题中猜测(如何检查数组是否包含一个值,但以串联为单位),据我了解,这是一个很好的解决方案。

def check_substring(string, letters):
    word = list(string)
    return any(letters == word[i:i+2] for i in range(len(word) - 1))


word = "hello"
print(check_substring(word, ["h","e"]))

Guessing from your question title (how to check if array contains a value but in series), this is a great solution for your problem, as far as I understand it.

def check_substring(string, letters):
    word = list(string)
    return any(letters == word[i:i+2] for i in range(len(word) - 1))


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