在Python2.7中,可以通过非数字字符从列表中删除项吗?

2024-04-26 10:51:42 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有可能在未来更新的列表,但我不想打印出所有的结果。我想将打印的列表限制为不包含“+”号或“.”的项目,只保留我想要其名称的文件夹。你知道吗

myList = ['+Map_Design', 'for_pl', 'land_comm', 'FILE LIST - Shortcut (2).lnk', 
          'SiteLocatorMap.mxd', 'Thumbs.db']

我试过用。。。你知道吗

[x for x in myList if not '.' in x]

以及

[x for x in myList if not . in x]

没有运气。这是我试图删除的字符(,+)的问题还是我使用了错误的代码。你知道吗

我要找的是一个列表,在这个例子中只包含['for\u pl','land\u comm']。你知道吗


Tags: 项目in文件夹名称map列表forif
1条回答
网友
1楼 · 发布于 2024-04-26 10:51:42

我猜你的全部代码

myList = ['+Map_Design', 'for_pl', 'land_comm', 'FILE LIST - Shortcut (2).lnk', 'SiteLocatorMap.mxd', 'Thumbs.db']
[x for x in myList if not '.' in x]
[x for x in myList if not '+' in x]
print myList

列表理解本身并不会修改您正在迭代的内容。尝试将结果赋回myList

myList = ['+Map_Design', 'for_pl', 'land_comm', 'FILE LIST - Shortcut (2).lnk', 'SiteLocatorMap.mxd', 'Thumbs.db']
myList = [x for x in myList if not '.' in x]
myList = [x for x in myList if not '+' in x]
print myList

结果:

['for_pl', 'land_comm']

额外风格提示:'.' not in xnot '.' in x更惯用。你知道吗

相关问题 更多 >