简体   繁体   English

列表中的“分组”项目

[英]"group" items in list

I have [string, int,int],[string, int,int]... kind of list that I want to group with a different list我有[string, int,int],[string, int,int]...类型的列表,我想用不同的列表分组

[string1, int1,int1] + [string2, int2,int2] = ["string+string2", int1+int1+int2+int2]

the History goes like I have already made import function that gets me compounds:历史就像我已经制作了让我复合的导入功能:

ex[Ch3, 15.3107,15.284] kinda like this... ex[Ch3, 15.3107,15.284] 有点像这样......

I have a function that gives me: dictionary{0:"CH3"} and another that gives me: List ["CH3",30.594700000000003]我有一个函数给我: dictionary{0:"CH3"}和另一个给我的函数: List ["CH3",30.594700000000003]

def group_selectec_compounds(numCompound,values)

values can be list of list that have everything I also have dic made that is something like this {0:["CH4"],...} numCoumpound should be various variables (I think) or tuple of keys?值可以是列表列表,其中包含我也有 dic 制作的所有内容,类似于{0:["CH4"],...} numCoumpound应该是各种变量(我认为)或键元组? So I can do the math for the user.所以我可以为用户做数学计算。

In the end I want something like: ["CH3+CH4",61.573] it can also be: ["CH3+CH4+H2SO4",138.773]最后我想要的是: ["CH3+CH4",61.573]也可以是: ["CH3+CH4+H2SO4",138.773]

I would solve this using '+'.join , sum and comprehensions:我会使用'+'.joinsum和 comprehensions 来解决这个问题:

>>> data = [['string1', 2, 3], ['string2', 4, 5], ['string3', 6, 7]]
>>> ['+'.join(s for s, _, _ in data), sum(x + y for _, x, y in data)]
['string1+string2+string3', 27]

First, create a dictionary that stores the location of the type:首先,创建一个存储类型位置的字典:

helper = {}
for elem in lst1:
  elemType = str(type(elem))
  if elemType not in helper:
    helper[elemType] = lst1.index[elem]

Now you have a dictionary that indexes your original list by type, you just have to run the second list and append accordingly:现在你有一个按类型索引原始列表的字典,你只需要运行第二个列表并相应地附加:

for elem in lst2:
  elemType = str(type(elem))
  if elemType not in helper:
    #in case list 2 contains a type that list 1 doesn't have
    lst1.append(elem)
    helper[elemType] = lst1.index[elem]
  else:
    lst1[helper[elemType]] += elem

Hope this makes sense!希望这是有道理的! I have not vetted this for correctness but the idea is there.我没有审查这个的正确性,但这个想法就在那里。

Edit: This also does not solve the issue of list 1 having more than 1 string or more than 1 int, etc., but to solve that should be trivial depending on how you wish to resolve that issue.编辑:这也不能解决列表 1 具有超过 1 个字符串或超过 1 个 int 等的问题,但根据您希望如何解决该问题,解决该问题应该很简单。

2nd Edit: This answer is generic, so it doesn't matter how you order the strings and ints in the list, in fact, lst1 can be [string, int, double] and lst2 can be [int, double, string] and this would still work, so it is robust in case the order of your list changes第二次编辑:这个答案是通用的,所以你如何对列表中的字符串和整数进行排序并不重要,事实上,lst1 可以是 [string, int, double] 而 lst2 可以是 [int, double, string] 和这仍然有效,因此在您的列表顺序发生变化的情况下它很强大

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM