将字符索引为元组中的整数并将其用于字典

2024-09-29 01:35:47 发布

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

我有一个元组列表,例如:

corp = [('h','somename'), 
        ('h','someothername'),
        ('a','awholeothername'),
        ('a','name again'),
       ]

我希望创建一个字典,其中第一个索引h或a以

for x,y in corp:
    if x == 'h':
       x = 1
    x = 0 

但这似乎不起作用,因为我们无法在Python中进行项分配。将所有第0个索引映射到整数后

我尝试的是:

dicts = {'nationality': {} , 'name': {}}
for x,y in data:
    dicts['nationality'] == x
    dicts['name'] == y 

但是不起作用。我通常远离字典,即使在两年的编码工作之后也是如此,这让我感到很不舒服


Tags: namein列表forif字典整数元组
2条回答

您可以使用.items()迭代字典的键和值:

data = {'nationality': {} , 'name': {}}

for x, y in data.items():
    if x == 'h':
       corp[x] = 1  # If you want to actually edit the value, you have to do it this way.
    corp[x] = 0 

另外,请注意您应该使用一个=来完成作业


要编辑列表,请找到要更改的索引并在分配中使用:

for i, value in enumerate(corp):
    x, y = value
    if x == 'h':
       corp[i][0] = 1
    corp[i][0] = 0

Imo(如果我正确理解了您的问题)一个非常好的defaultdict用例:

from collections import defaultdict

corp = [('h','somename'), 
        ('h','someothername'),
        ('a','awholeothername'),
        ('a','name again'),
       ]

mapping = defaultdict(lambda: -1)
mapping['h'] = 1
mapping['a'] = 0

result = [(mapping[key], value) for key, value in corp]
print(result)

产生

[(1, 'somename'), (1, 'someothername'), (0, 'awholeothername'), (0, 'name again')]

这样做的好处是,元组的第一个位置上可以有任何内容(它将产生一个-1

相关问题 更多 >