python - python:检查一个变量是否有值
问题描述
我是 python 新手,正在使用 while 循环。我有一个场景,我需要检查一个变量是否有一个与之关联的值或字符串,并找到这个我不应该在 python 中使用内置函数。我尝试在 while 循环中使用以下内容,但它的抛出错误如下所示:
代码:
li = [1,2,3,4,5,"string1", "string2"]
print ("Test of List")
i = 0
while (li[i] != ""):
print (li[i])
i = i + 1
print ("Val of i :",i)
输出:
Test of List
1
2
3
4
5
string1
string2
Traceback (most recent call last):
File "C:\Users\sesubra2\Desktop\python_codes.py", line 71, in <module>
while (li[i] != ""):
IndexError: list index out of range
解决方案
li = [1, 2, 3, 4, 5, "string1", "string2"]
print ("Test of List")
i = 0
while (i < len(li)):
if(li[i] != ""):
print (li[i])
i = i + 1
print ("Val of i :", i )
原因是您的 while 语句是错误的。试试看
如果你仍然喜欢你的逻辑,试试看
def checkValiable(array, i):
while (array[i] != ""):
print (li[i])
i = i + 1
if(i < len(array) - 1):
del array[i];
checkValiable(array, i - 1)
return
print ("Val of i :", i)
return array
li = [1, 2, 3, 4, 5,"", "string1", "string2"]
print ("Test of List")
i = 0
li.append("")
checkValiable(li, i)
推荐阅读
- android - 尝试从 DialogFragment 获取回调到片段,但应用程序崩溃
- javascript - 带有分钟、秒和毫秒的 Javascript 降序计时器
- django - 如何使用内联结构迭代表单集
- apache-flink - Apache Flink:我可以在 WindowFunction 中获取关键字段的名称吗?
- mysql - GROUP 和 ORDER Mysql 在列中获取不同的数据
- node.js - 如何在 npm package.json git 项目中更新 Git 哈希?
- .net - 赋值 null 时,SqlParameter“消失”?
- java - 是否可以打开和关闭@Secured注解
- elasticsearch - 安装 Logstash 错误 Errno::ENOMEM Duplicate
- reactjs - undefined 不是对象(评估 RNDeviceinfo.getMacAddress) Expo React native