这个if语句是否符合检查集合大小增加的条件?

2024-09-26 18:03:19 发布

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

以下if语句是否满足此条件:

If the set increases in size (indicating this word has not been processed before), add the word to the dict as a key with the value being the new length of the set

还是我找错树了?你知道吗

s = set()
d = dict()

text = input("Your text here: ")
for word in text.strip().split():
    if word not in s:
        s.add(word)
        d[word] = len(s)

print(d)

Tags: thetextinaddsizeifnot语句
2条回答

也许更简单的方法

d = dict()
for word in raw_input('enter:').strip().split():
    if word not in d:
        d[word]=len(word)

print d.keys()

不,我认为那不太对。听起来你应该:

  1. 将单词添加到集合中。你知道吗
  2. 测试其长度是否增加。你知道吗
  3. 如果是的话,把这个词加到字典里。你知道吗

您的代码应该如下所示:

s = set()
d = dict()

text = input("Your text here: ")
for word in text.strip().split():
    old_len = len(s)
    s.add(word)
    new_len = len(s)
    if new_len > old_len:
        d[word] = len(s)

print(d)

相关问题 更多 >

    热门问题