键和列表作为其值的字典。如何识别列表中的项目,并移动到另一个列表?(python)
在我的comp-sci课程中,我们刚刚谈到了字典。我正在尝试找出如何从字典中的列表中删除一个项目,并将其移动到另一个列表中 比如说,键和列表作为其值的字典。如何识别列表中的项目,并移动到另一个列表?(python),python,list,dictionary,Python,List,Dictionary,在我的comp-sci课程中,我们刚刚谈到了字典。我正在尝试找出如何从字典中的列表中删除一个项目,并将其移动到另一个列表中 比如说, dict1={ 'colors':[red,blue,green], 'sweaters':[mine, his, hers]} 比方说,我想检查字典里是否有“red”,而且是。那么,我怎样才能把它从“颜色”中去掉,并添加到“毛衣”中呢?列表部分把我甩了 这就是我到目前为止的功能(实际问题) `def nowRead(你的字典,标题): 您是否知道(a)如何访问
dict1={ 'colors':[red,blue,green], 'sweaters':[mine, his, hers]}
比方说,我想检查字典里是否有“red”,而且是。那么,我怎样才能把它从“颜色”中去掉,并添加到“毛衣”中呢?列表部分把我甩了
这就是我到目前为止的功能(实际问题)
`def nowRead(你的字典,标题):
您是否知道(a)如何访问字典中的对象;(b)如何在列表中添加内容?这些就是你在这里需要的行动
您还需要弄清楚如何从列表中删除,但以上内容将为您提供大部分方法。尝试以下方法:
colorsToLook = ['red']
dVals = { 'colors': ['red','blue','green'], 'sweaters':['mine', 'his', 'hers']}
for k in set(colorsToLook):
if k in dVals['colors']:
dVals['sweaters'].append(dVals['colors'].pop(dVals['colors'].index(k)))
你在找像这样的东西
dict1['colors'].remove('red')
dict1['sweaters'].append('red')
您可以在中找到更多列表方法
另外,如果您对使用Python感兴趣,这是一个很好的开始
dict1={ 'colors':['red','blue','green'], 'sweaters':['mine', 'his', 'hers']}
def change_lists(target):
try:
dict1['colors'].remove(target)
dict1['sweaters'].append(target)
except ValueError:
pass
结果:
>>> dict1
{'colors': ['red', 'blue', 'green'], 'sweaters': ['mine', 'his', 'hers']}
>>> change_lists('red')
>>> dict1
{'colors': ['blue', 'green'], 'sweaters': ['mine', 'his', 'hers', 'red']}
>>> change_lists('black')
>>> dict1
{'colors': ['blue', 'green'], 'sweaters': ['mine', 'his', 'hers', 'red']}
dict1['colors'].remove('red')
dict1['sweaters'].append('red')
dict1={ 'colors':['red','blue','green'], 'sweaters':['mine', 'his', 'hers']}
def change_lists(target):
try:
dict1['colors'].remove(target)
dict1['sweaters'].append(target)
except ValueError:
pass
>>> dict1
{'colors': ['red', 'blue', 'green'], 'sweaters': ['mine', 'his', 'hers']}
>>> change_lists('red')
>>> dict1
{'colors': ['blue', 'green'], 'sweaters': ['mine', 'his', 'hers', 'red']}
>>> change_lists('black')
>>> dict1
{'colors': ['blue', 'green'], 'sweaters': ['mine', 'his', 'hers', 'red']}