python - 无法删除列表中的“某些”空项目
问题描述
我已经编码了一段时间,但最近我遇到了一个矛盾的问题。出于某种原因,在打印的“第三阶段”中,列表中仍有空项目。这很奇怪,因为代码的一部分应该删除所有为空的项目,但仍然有一些。. . .
我发现的唯一问题是包含两个逗号连接的字符串 " ,,
" 并且中间的逗号不会被删除。
不幸的是,我无法解决这个问题,也没有找到任何可以帮助我解决问题的方法。预先感谢您提供的任何帮助!
SpecificPlayerChat = "!get specific player chat log: , ,, ,,, username | category"
#Removing all spaces found within the string
SpecificPlayerChat = SpecificPlayerChat.replace(" ","").strip().replace("\n","")
print("First Stage:", SpecificPlayerChat)
#Store the string username & category data only and split the rest into a "junk" string
junk,SpecificPlayerChatData = SpecificPlayerChat.split(":")
print("Second Stage:", SpecificPlayerChatData)
junk = "" #This string deleted the unwanted string
#Split the usernames and categories into two separate strings
usernames,categories = SpecificPlayerChatData.split("|")
print("Third Stage:", usernames)
#Split the multiple words or "no words" into an item each to be store in a list
usernamelist = []
categorylist = []
usernamelist = usernames.split(",")
categorylist = categories.split(",")
#remove any empty items
print(" Print Empty items:")
for item in usernamelist:
if item is '':
usernamelist.remove(item)
print(" Empty Item Detected!")
print("Third Stage ", usernamelist)
解决方案
这个打印显示了吗?
print(" Empty Item Detected!")
试试这个而不是删除:
将其替换为:
for item in usernamelist:
if item is '' or item is null:
usernamelist.remove(item)
print(" Empty Item Detected!")
有了这个:
for item in usernamelist:
if item is '' or item is null:
del usernamelist[usernamelist.index(item)]
print(" Empty Item Detected!")
参考: https : //www.w3schools.com/python/ref_keyword_del.asp,https: //www.programiz.com/python-programming/methods/list/index
推荐阅读
- python - 有没有办法在 PyQt5 中设置 QTextEdit.placeholderText() 的对齐方式?
- c++ - 使用 openCV/C++ 根据模型重构正方形
- java - 使用 Liquibase 运行自定义的 drop-first 脚本
- c# - 具有超过 1 个条件检查的三元运算符
- python - python图像更改tkinter和PIL
- android - 设置使用 exoplayer 播放的持续时间
- gcc - 如何知道我的代码是在 CPU 还是 GPU 上运行?
- python-3.x - 如何查询字段名称中有点的熊猫数据框
- javascript - 如何使用 JQuery 获取文件的下载时间?
- reactjs - 如何使用有关路由更改的新数据重新呈现反应类组件