gpt4 book ai didi

python - 搜索并添加 python 列表

转载 作者:太空宇宙 更新时间:2023-11-03 14:32:52 24 4
gpt4 key购买 nike

我有一个 TList,它是一个列表列表。如果以前不存在,我想将新项目添加到列表中。例如,如果项目 I 不存在,则添加到 Tlist 否则跳过。是否有更 pythonic 的方式来做到这一点?注意:起初 TList 可能是空的,并且在此代码中添加了元素。例如添加 Z 后,TList = [ [A,B,C],[D,F,G],[H,I,J],[Z,aa,bb]]。其他元素基于Z的计算。

    item = 'C'  # for example this item will given by user
TList = [ [A,B,C],[D,F,G],[H,I,J]]
if not TList:
## do something
# check if files not previously present in our TList and then add to our TList
elif item not in zip(*TList)[0]:
## do something

最佳答案

由于每个子列表中的第一个条目似乎是某种键,而其余条目以某种方式从该键派生,因此字典可能是更合适的数据结构:

vals = {'A': ['B','C'], 'D':['F','G'], 'H':['I','J']}
if 'Z' in vals:
print 'found Z'
else:
vals['Z'] = ['aa','bb']

关于python - 搜索并添加 python 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7705128/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com