2

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) ]
4

3 回答 3

1

您正在使用标准库函数作为变量名。这就是 set() 操作失败的原因。

将 list = [] 更改为 my_list = [] 或其他内容...

于 2012-12-17T00:33:07.730 回答
0

set(list)将比较列表中的成员,在您的情况下

'H2O2Y2','R3O2','Y2S3'

没有一个是相同的。

首先 ''.join() 将列表项放入一个字符串 - 我相信是一个字符列表 - 然后使用 set() 查找唯一字符:

def unique_elements(group):

    return list(set(''.join(group)))
于 2013-01-17T23:51:18.753 回答
0

此函数消除列表中的重复项:

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

那样有用吗?

来自这个网站

于 2012-12-17T01:30:16.893 回答