I have [string, int,int],[string, int,int]...
kind of list that I want to group with a different list
[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...
I have a function that gives me: dictionary{0:"CH3"}
and another that gives me: 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? 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]
I would solve this using '+'.join
, sum
and 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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.