写这篇文章的更好方法?

2024-04-20 08:52:14 发布

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

我正在检查字典中单词的切片部分是否在列表中,这样就可以知道字典值中以“;”结尾或最后一个的单词是否是基本形式的名词。你知道吗

我这里有代码:

dict = {"devotion": "andumus; pühendumust", "devotional": "vagasse",
        "devour": "kugistama; alla neelama", "devoured": "neelatud"}
endings2 = ["es", "te", "de", "st", "el", "le", "lt", "ks", "ni", "na",  "ta",  "ga", "id"]
endings3 = ["sse", "tte"]

for k, v in sorted(dict.items()):
    for x in v.split():
        if ((x[-1:] == ';' or x == v.split()[-1])
             and (x[-3:-1] not in endings2 and x[-4:-1] not in endings3
                 and x[-2:] not in endings2 and x[-3:] not in endings3)):
            print(k, x)

它工作,但它是一种硬编码。我更愿意只使用一个列表作为案例/结尾。你知道吗


Tags: andin列表for字典结尾not切片
2条回答

而不是

if x[-1] == ";" ...

你可以用

if x.endswith(';') ...

要查看单词在列表中是否有结尾,可以去掉分号并在结尾处循环:

word = x.strip(';')
for ending in endings:
  if word.endswith(ending):
     ...

这样你就不必区别对待两个和三个字母的结尾。你知道吗

你问起Python。在我看来,使用python提供的特性是最具python风格的方法。你知道吗

^{}

str.endswith(suffix[, start[, end]])

Return True if the string ends with the specified suffix, otherwise return False. suffix can also be a tuple of suffixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that position.

Changed in version 2.5: Accept tuples as suffix.

所以它接受tuple,为什么不使用它:

endings = tuple(endings2 + endings3)

if not x.endswith(endings):
    print(k, x)

而不是在这里使用any和理解或手动循环。你知道吗


但是还有另一个肾盂指南(import this

[...]

Simple is better than complex.

[...]

There should be one and preferably only one obvious way to do it.

[...]

我说的是

if (x[-1:] == ';' or x == v.split()[-1])
#                 ^^^^^^^^^^^^^^^^^^^^^

你到底想做什么。这会比较你的x,它是v.split()[i]v.split()[-1]?我认为这种情况至少值得一提。为什么检查它是否是整个字符串中的最后一个子字符串很重要?你知道吗

这可能不是你想要的,但举一个“pythonic”方法的例子:

for k, v in sorted(dict.items()):
    for x in v.split(';'):           # split at ';'
        x = x.strip()                # remove leading and trailing whitespaces
        if not x.endswith(endings):  # make sure it doesn't end with a forbidden ending
            print(k, x)

或:

for k, v in sorted(dict.items()):
    for x in v.split():              # split at whitespaces
        x = x.rstrip(';')            # remove TRAILING ";"
        if not x.endswith(endings):
            print(k, x)

相关问题 更多 >