GVKun编程网logo

Python:使用索引作为值将列表转换为字典(python以列表为索引的列表)

7

最近很多小伙伴都在问Python:使用索引作为值将列表转换为字典和python以列表为索引的列表这两个问题,那么本篇文章就来给大家详细解答一下,同时本文还将给你拓展c#–将列表转换为字典并使用linq

最近很多小伙伴都在问Python:使用索引作为值将列表转换为字典python以列表为索引的列表这两个问题,那么本篇文章就来给大家详细解答一下,同时本文还将给你拓展c# – 将列表转换为字典并使用linq汇总值、python – 如何将元组列表转换为字典、python – 将列表转换为多值dict、python – 将列表转换为字典等相关知识,下面开始了哦!

本文目录一览:

Python:使用索引作为值将列表转换为字典(python以列表为索引的列表)

Python:使用索引作为值将列表转换为字典(python以列表为索引的列表)

我正在尝试转换以下列表:

list = [''A'',''B'',''C'']

像这样的字典:

dict = {''A'':0, ''B'':1, ''C'':2}

我尝试了其他职位的答案,但没有任何帮助。我现在有以下代码:

{list[i]: i for i in range(len(list))}

这给了我这个错误:

unhashable type: ''list''

任何帮助深表感谢。谢谢。

答案1

小编典典

您可以从内置的枚举中获取列表的索引。您只需要反转索引值映射并使用字典理解来创建字典

>>> lst = [''A'',''B'',''C'']>>> {k: v for v, k in enumerate(lst)}{''A'': 0, ''C'': 2, ''B'': 1}

哦,永远不要将变量命名为内置变量或类型。

c# – 将列表转换为字典并使用linq汇总值

c# – 将列表转换为字典并使用linq汇总值

我有列表,即List< Field>.这个Field类包含一个代码和一个值属性以及其他字段,我希望能够使用 linq来总结相同代码的所有值.

我知道我可以遍历我的列表并使用以下代码将其添加到字典中,但我确信必须有一个更简洁的方法来执行此操作:

if (totals.ContainsKey(code))
{
  totals[code] += value;
}
else
{
  totals.Add(code,value);
}

有任何想法吗?

我找到了类似的东西,但这适用于列表>这不是我所拥有的:

var result = Sales.SelectMany(d => d) // Flatten the list of dictionaries
             .GroupBy(kvp => kvp.Key,kvp => kvp.Value) // Group the products
             .ToDictionary(g => g.Key,g => g.Sum());

来自本文[使用Linq in< List< Dictionary< string,int>>]的总和金额Sum amount using Linq in <List<Dictionary<string,int>>

有任何想法吗?我总是可以将我的代码更改为包含字典< string,Field>但我确信必须有一种方法可以用列表和linq来做到这一点.

谢谢.

我有列表,我希望能够使用linq来总结相同代码的所有值.

我知道我可以遍历我的列表并使用以下代码将其添加到字典中,Field>但我确信必须有一种方法可以用列表和linq来做到这一点.

谢谢.

更新:

对不起,我想我省略了有关上述内容的重要部分.该列表包含在另一个列表中,即List> myitemList;其中包含其他可能需要进一步过滤的无关字段.我不确定???

注意:抱歉格式化再次搞砸了!

为此提供一些上下文:

Item1(List类型)

商品名称价值

(第1项)第1类
(第2项)描述测试
(第3项)守则A.
(第4项)净100.00

Item2(List类型)

商品名称价值

(第1项)第2类
(第2项)说明测试1
(第3项)代码B.
(第4项)净95.55

Item3(List类型)

商品名称价值

(第1项)第2类
(第2项)说明测试2
(第3项)守则A.
(第4项)净35.95

正如您所看到的,List列表中的每个列表包含4个字段条目,其中我的字段定义为Name(String)和Value(Object)

然后将这些列表中的每一个添加到主列表中.所以我需要遍历主列表,然后我想最终得到一个字典,其中包含每个列表的“代码”和“网络”的总和.所以最后,我应该结束

A,135.95
B,95.55

我不知道上面是否有意义.我希望它能做到!

UPDATE

事实上,我正在处理一个列表>实际上并没有因为我当时想要总结一个列表而有所不同,所以提供答案是正确的!谢谢!

解决方法

您发布的代码几乎就是您所需要的 – 要在列表中使用它,您需要稍微简化它:
var result = myList                             // No flattening
    .GroupBy(x => x.Code)                       // Group the items by the Code
    .ToDictionary(g => g.Key,g => g.Sum(v => v.Value)); // Total up the values

python – 如何将元组列表转换为字典

python – 如何将元组列表转换为字典

我有一个元组列表,如下所示:

lst_of_tpls = [(1,'test2',3,4),(11,'test12',13,14),(21,'test22',23,24)]

我想将它转换为字典,使它看起来像这样:

mykeys = ['ones','text','threes','fours']
mydict = {'ones': [1,11,21],'text':['test2','test22'],'threes': [3,23],'fours':[4,14,24]}

我试图枚举lst_of_tplslike所以:

mydict = dict.fromkeys(mykeys,[])
for count,(ones,text,threes,fours) in enumerate(lst_of_tpls):
    mydict['ones'].append(ones)

但是这使得我希望在’ones’中看到的值也在其他“类别”中:

{'ones': [1,'text': [1,'threes': [1,'fours': [1,21]}

另外,我想保持我的灵活性.

解决方法

您可以应用两次拉链以找到正确的配对:

lst_of_tpls = [(1,24)]
mykeys = ['ones','fours']
new_d = {a:list(b) for a,b in zip(mykeys,zip(*lst_of_tpls))}

输出:

{
 'ones': [1,'text': ['test2','fours': [4,24]
}

python – 将列表转换为多值dict

python – 将列表转换为多值dict

我有一个列表:

pokemonList = ['Ivysaur','Grass','Poison','','Venusaur','Charmander','Fire',''...]

请注意,模式是’口袋妖怪名称’,’它的类型’,”…下一个口袋妖怪

口袋妖怪有单一和双重形式.我如何对此进行编码,以便每个口袋妖怪(键)都将其各自的类型应用为其值?

到目前为止我得到了什么:

types = ("","Grass","Poison","Fire","Flying","Water","Bug","Dark","fighting","normal","Ground","Ghost","Steel","Electric","Psychic","Ice","Dragon","Fairy")
pokeDict = {}
    for pokemon in pokemonList:
        if pokemon not in types:
            #the item is a pokemon,append it as a key
        else:
            for types in pokemonList:
                #add the type(s) as a value to the pokemon

正确的字典将如下所示:

{Ivysaur: ['Grass','Poison'],Venusaur['Grass',Charmander:['Fire']}

解决方法

只需迭代列表并适当地构造dict的项目.

current_poke = None
for item in pokemonList:
    if not current_poke:
        current_poke = (item,[])
    elif item:
        current_poke[1].append(item)
    else:
        name,types = current_poke
        pokeDict[name] = types
        current_poke = None

python – 将列表转换为字典

python – 将列表转换为字典

我有一个列表,其中包括:

list = [(Year,'make','model')]

使用Python,是否可以将其转换为dict,其中年份是关键:

dict = {Year : {'Make' : [models]}}

例如:

{
2013:{
'Scion' : ['FR-S,' 'tC'],'Subaru' : ['BRZ'],'Toyota' : ['Land Cruiser','Venza'],}
2012:{
'Scion' : ['FR-S,'Toyota' : ['Venza'],}

}

解决方法

>>> values = [('Year','model')]
>>> result = {}
>>> for lst in values:
...     leaf = result
...     for path in lst[:-2]:
...        leaf = leaf.setdefault(path,{})
...     leaf.setdefault(lst[-2],list()).append(lst[-1])
...
>>> result
{'Year': {'make': ['model']}}

关于Python:使用索引作为值将列表转换为字典python以列表为索引的列表的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于c# – 将列表转换为字典并使用linq汇总值、python – 如何将元组列表转换为字典、python – 将列表转换为多值dict、python – 将列表转换为字典等相关内容,可以在本站寻找。

本文标签: