我正在尝试完成以下任务:

Iterate a list
    if an element (string) does not have a '$' at the first position
        apply a '$'  and append the new value to the array


我正在尝试类似的东西:

  symbols = ['aol', 'goog', ...]
  (symbols.append('$'+val) if '$' != val[0] for val in symbols)


但是我遇到语法错误。
任何帮助表示赞赏。

最佳答案

遍历列表的浅表副本,并使用$检查str.startswith()

In [81]: symbols = ['aol', 'goog','$foo','bar']

In [82]: for x in symbols[:]:
    if not x.startswith('$'):
        symbols.append('$'+x)
   ....:

In [83]: symbols
Out[83]: ['aol', 'goog', '$foo', 'bar', '$aol', '$goog', '$bar']

关于python - Python方式-迭代数组,检查索引处的元素,将新字符串附加到数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14472298/

10-12 14:07