如果某个项目存在于我的数据结构中,请检查并使用它

2024-09-22 14:39:29 发布

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

我有一个项目清单,例如

item_list = ['char_model_..._main', 'char_model_..._main_default', 'char_rig_..._main', 'char_rig_..._main_default',  'char_acc__..._main']

虽然我能够从列表中得到我想要的某些东西,并且我将其编码如下(不是以一种非常庄重的方式,但它会给我反馈):

item_wanted=[]
for item in item_list:
    if item.startswith("char_model") and (item.endswith("main") or item.endswith("main_default")):
        item_wanted.append(item)

因此,虽然我能够得到我想要的项目,使得现在的my item_wanted列表包含'char_model_..._main', 'char_model_..._main_default',但我应该如何编码它,以便如果'main'存在,就使用它,否则就使用'main_default'?你知道吗


Tags: 项目default编码列表formodelmain方式
3条回答

嗯,我不完全明白你的意图,但也许你可以试着把它分开

if item.startswith("char_model") :
  if item.endswith("main"):
    #do your thing if its "char_model...main"
  elif item.endswith("main_default):
    #do your thing if its "char_model...main"

希望这有帮助

我的方法是简单地使用两个变量并对输入列表进行一次迭代。它能够处理输入中的多个“good”“best”匹配。为了简化,我使用了数字列表,对于mainmain_default部分,我习惯于使用1而不是2。你知道吗

代码:

def match(items):
    found1 = None
    found2 = None
    for i in items:
        if (i==1):
            found1 = i
        elif (i==2):
            found2 = i
    return found1 or found2

print (match([2,1]))
print (match([3,2]))
print (match([4,3]))

输出:

1
2
None

看到这个运行在https://ideone.com/bBj5Op

将有效项分为包含默认值的项和不包含的项。然后,迭代那些dodefault结尾的键,并尝试在另一个列表中找到相同的键(当然要删除结尾)。如果它不存在,就意味着我们必须使用默认值,如果它存在,我们就保持原样。你知道吗

item_wanted  = []
item_default = []

for item in item_list:
    if item.startswith("char_model"):
        if item.endswith("main_default"):
            item_default.append(item)
        elif item.endswith("main"):
            item_wanted.append(item)

for potential in item_default:
    if potential[:-8] not in item_wanted: #Look for the key without default
        item_wanted.append(potential)     #Append it if not present

相关问题 更多 >