python 中 if 语句的生成器
或者如何在修改后的列表中使用 if 语句。
我已经阅读 StackOverflow 一段时间了(感谢大家)。我喜欢它。我还看到您可以发布问题并自己回答。抱歉,如果我重复了,但我没有在 StackOverflow 上找到这个特定的答案。
- 如何验证一个元素是否在列表中但同时修改它?
我的问题:
myList = ["Foo", "Bar"]
if "foo" in myList:
print "found!"
由于我不知道列表中元素的大小写,我想与小写列表进行比较。显而易见但丑陋的答案是:
myList = ["Foo", "Bar"]
lowerList = []
for item in myList:
lowerList.append(item.lower())
if "foo" in lowerList:
print "found!"
我可以做得更好吗?
Or How to if-statement in a modified list.
I've been reading StackOverflow for a while (thanks to everyone). I love it. I also seen that you can post a question and answer it yourself. Sorry if I duplicate, but I didn't found this particular answer on StackOverflow.
- How do you verify if a element is in a list but modify it in the same time?
My problem:
myList = ["Foo", "Bar"]
if "foo" in myList:
print "found!"
As I don't know the case of the element in the list I want to compare with lower case list. The obvious but ugly answer would be:
myList = ["Foo", "Bar"]
lowerList = []
for item in myList:
lowerList.append(item.lower())
if "foo" in lowerList:
print "found!"
Can I do it better ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
列表推导式:
然后您可以执行类似
if "foo" in lowerlist
的操作,或者使用if "foo" in [item.lower() for item in mylist]
完全绕过临时变量代码>List comprehensions:
Then you can do something like
if "foo" in lowerlist
or bypass the temporary variable entirely withif "foo" in [item.lower() for item in mylist]
怎么样:
顺便说一句。你不应该调用你的变量
list
,因为这个词已经被list
类型使用。How about:
BTW. you shouldn't call your variable
list
as this word is already used bylist
type.请不要使用列表作为变量名,这是将生成器放入变量并演示的版本,该生成在找到答案后停止并且没有耗尽生成器:
Please do not use list as variable name, here is version which puts generator to variable and demonstrates, that generation stopped after finding the answer and did not exhaust the generator:
这结合了生成器表达式的内存优势和删除重复项带来的速度增益:
This combines the memory advantages of a generator expression with the speed gains from removing duplicates: