我正在学习创建一个“if”语句块来检查某些条件,我想让它们识别列表中是否有空的引号。
举个例子:
favourite_fruit = []
if len(favourite_fruits) == 0:
print('Fruits are an important part of one's diet')
###This code works which is great as long as the list is empty in terms of it's length.如果列表不是空的,并且他们有这样的东西:'apple‘,但是缺少另一个像’date‘这样的水果,那么我会告诉它说:
if 'dates' not in favourite_fruit and len(favourite_fruit) != 0:
print ('Have you tried Dates? They are high in fibre, a good source of which, can help prevent constipation by promoting bowel movements.') 但问题是,如果我键入:
favourite_fruit = ['']此列表的长度为1,但其中没有任何内容,因此它将打印日期引用,而不是“水果很重要”引用。
有没有办法让python识别列表中没有实际写入的内容?
我基本上是个初学者,所以我还在学习。
以下是我尝试过的方法:
favourite_fruit = ['']
if 'dates' not in favourite_fruit and len(favourite_fruit) != 0 and favourite_fruit != "" and favourite_fruit != "\"\"" and favourite_fruit != '' and favourite_fruit != '\'\'':
print ('Have you tried Dates? They are high in fibre, a good source of which, can help prevent constipation by promoting bowel movements.')但它仍然不起作用。
发布于 2021-10-01 20:12:44
奇怪为什么列表中有空字符串。
无论如何,假设你想忽略空字符串,你可以先过滤你的列表。在Python中,这通常是通过以下语法实现的,这称为列表理解:
favourite_fruit = [f for f in favourite_fruit is f != ""]['']变成了[] (空列表),['apple', '']变成了['apple'],等等。
旁注:在Python语言中,非空列表是真的,空列表是假的,所以if len(favourite_fruits) == 0可以写成if favourite_fruits。
发布于 2021-10-01 20:38:47
有没有办法让python来识别列表中没有任何实际写入的内容?
空字符串是假的,所以您需要做的就是检查favourite_fruit中的项的any是否为真。
any([]) => False
any(['']) => False
any(['dates']) => Truehttps://stackoverflow.com/questions/69411470
复制相似问题