简体   繁体   中英

Need to remove duplicates for a list with in a function

this is what i have so far:

def unique_element(group):
  list=[]
  for element in group:
      piece=parse_formula(element)
      for x in piece:
          list.append(x[0])


  return list #list(set(list)) 

I have the other function below but this is the one I am trying to fix. Right now it returns a function with a list of letters but I do not want repeating letters. Example:

unique_element(['H2O2Y2','R3O2','Y2S3'])
['H', 'O', 'Y', 'R', 'O', 'Y', 'S']

I thought using list(set(list)) would work but when i run the function i get:

unique_element(['H2O2Y2','R3O2','Y2S3'])

Traceback (most recent call last):

File "<stdin>", line 1, in <module>
File "_sage_input_61.py", line 10, in <module>
  exec compile(u'print _support_.syseval(python, u"unique_element([\'H2O2Y2\',\'R3O2\',\'Y2S3\'])", __SAGE_TMP_DIR__)
File "", line 1, in <module>

File "/sagenb/sage_install/sage-5.4-sage.math.washington.edu-x86_64-Linux/devel/sagenb-git/sagenb/misc/support.py", line 479, in syseval
  return system.eval(cmd, sage_globals, locals = sage_globals)
File "/sagenb/sage_install/sage-5.4-sage.math.washington.edu-x86_64-Linux/local/lib/python2.7/site-packages/sage/misc/python.py", line 56, in eval
    eval(z, globals)
File "", line 1, in <module>

File "", line 10, in unique_element

TypeError: 'list' object is not callable

other functions:

    from numpy import *
    from scipy import *
    from pylab import *
    import re
def parse_formula(formula):
'''Given a simple chemical formula, return a list of (element, multiplicity) tuples.

Example:
'H2SO4' --> [('H', 2.0), ('S', 1.0), ('O', 4.0)]


'''

return [ (elem, float(mul) if mul else 1.) for (elem, mul) in re.findall(r'([A-Z][a-z]*)(\d*)', formula) ]

You are using a standard library function as a variable name. That is why the set() operation is failing.

Change list = [] to my_list = [] or something else...

This function gets rid of duplicates in a list:

def f5(seq, idfun=None): 
    if idfun is None:
        def idfun(x): return x
    seen = {}
    result = []
    for item in seq:
        marker = idfun(item)
        if marker in seen: continue
        seen[marker] = 1
        result.append(item)
    return result

Does that work?

Came from this site .

set(list) will compare the members of the list, in your case

'H2O2Y2','R3O2','Y2S3'

none of which are identical.

First ''.join() the list items into one string -a character list I believe- and then use set() to find unique characters:

def unique_elements(group):

    return list(set(''.join(group)))

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.

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