python - 仅当单词的一部分不在列表中时才附加
问题描述
我有一个类似下面的列表,并想从中列出两个列表。如果第一个包含 S01_a,则 S01_b 应该在第二个列表中。
my_list = ['S01_a', 'S01_b', 'S02_a', 'S02_b', 'S03_a', 'S03_b', 'S04_a', 'S04_b']
我试过这个,但我不知道如何引用 list1 中项目的 [1:2] 字符。有没有人有解决方案?
stims = ["S01_a", "S01_b", "S02_a", "S02_b", "S03_a", "S03_b", "S04_a", "S04_b"]
l1 = []
l2 = []
for item in stims:
if item[1:2] not in l1:
l1.append(item)
else:
l2.append(item)
print(l1)
print(l2)
输出是:
['S01_a', 'S01_b', 'S02_a', 'S02_b', 'S03_a', 'S03_b', 'S04_a', 'S04_b']
[]
先感谢您。
解决方案
You can use any()
with a generator that tests item[1:3]
against each element of the list.
for item in stims:
if not any(item[1:3] == el[1:3] for el in l1):
l1.append(item)
else:
l2.append(item)
You need to use the slice [1:3]
. Remember, the second index is not inclusive, so [1:2]
just selects the digit 0
, not the two digits 01
, 02
, etc.
推荐阅读
- php - 一个数组包含空值和其他空值的数组差异问题
- ibm-mq - Open Liberty 中是否有连接 IBM MQ 的“功能”,相当于 Liberty Profile 中的 wmqJmsClient-2.0?
- vue.js - 无法在 Vue 中访问对象属性
- reactjs - Redux-Form 字段不会更新为在里面
- php - 使用 JQuery 为 AJAX POST 格式化表单数据并在 Laravel(或 PHP)中轻松访问?
- ruby - Rails 模板文件中缺少“)”
- mongodb - Mongoose 无法 findOne({_id : id}) 复制文档
- mysql - 具有不同值的 Codeigniter 更新表列
- javascript - 检查子数组分组的主键值
- python - CSV 上传问题