在下面的代码中,
splits = [(word[:i], word[i:]) for i in range(len(word) + 1)]
deletes = [L + R[1:] for L, R in splits if R]
对于给定的单词,if R
在最后的列表推导中表示什么?
为 splits
中的每个 L,R
组合返回 L+R[1:]
如果 R 是什么?存在吗?这是必要的检查吗?
最佳答案
你可以看看(假设你的word是一个字符串):
word = 'my_word'
print([(word[:i], word[i:]) for i in range(len(word) + 1)])
输出:
[('', 'my_word'),
('m', 'y_word'),
('my', '_word'),
('my_', 'word'),
('my_w', 'ord'),
('my_wo', 'rd'),
('my_wor', 'd'),
('my_word', '')]
你可以看到你的最后一个元素有一个空字符串,如果你不检查你的 R 因为你正在使用切片(R[1:]),你将得到:IndexError: string index out of range
,所以是的,在这种情况下有必要检查
if R
是在列表理解中进行检查的方式,与普通 if 语句中的逻辑相同。
可以看看here阅读更多关于 if/else inside list comprehension 的信息
关于python - 在列表理解中理解这个 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57789231/