由于以下原因,任何((x:=单词)语法无效:=

2024-09-27 07:31:20 发布

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

我试图实现的是获取在字符串中找到的单词(从列表中)

在这个令人敬畏的社区进行了一些搜索之后,我能够构建我所需要的:

tagstoserch= {
               "#WORD": {"First": "asd", "Last": "bcd"},
               "#ANOTHERWORD": {"First": "qwe", "User": "ytr"}
             }
teste = "asdasd asdasd#WORDasdasds#ANOTHERWORD"

if any((x := word) in teste for word in tagstoserch):
    print(tagstoserch[x]["First"])
else:
    print("N/A")

这在运行3.9 python的PC上运行得非常好

但当我尝试在RHEL上运行as 3.6时,它会出现以下错误:

if any((x := word) in teste for word in tagstoserch):
              ^
SyntaxError: invalid syntax

这与python版本有关吗

还是另一种方式更优雅?(真的需要找到他找到的一个词)


Tags: 字符串in列表forifany单词社区
2条回答

你可以用这样的东西

[tagstoserch[word]['First'] if word in teste else 'N/A' for word in tagstoserch ]

如果需要打印,可以使用此列表上的for循环进行打印

for word in tagstoserch:
    if word in teste:
        print(tagstoserch[word]["First"])
        break
else:
    print("N/A")

相关问题 更多 >

    热门问题