以原始顺序获取列表元素

时间:2015-08-01 13:26:02

标签: python for-loop

我目前的代码:

>>> sent=['attachment', '(1.', '=', '+EDT)', 'Details']
>>> [w[1:] for w in sent if w.startswith(('(', '+'))]+[w for w in sent if not w.startswith(('(', '+'))]

输出:

['1.', 'EDT)', 'attachment', '=', 'Details']

我想这样:

['attachment','1.', '=','EDT)', 'Details']

保持原始秩序。

我不想使用re.replace,我只想使用w.startswith()

2 个答案:

答案 0 :(得分:2)

要在保持原始顺序的同时使用startswith(),您需要在一个列表理解中执行操作。我们可以使用conditional expression

来做到这一点
sent = ['attachment', '(1.', '=', '+EDT)', 'Details']
print([w[1:] if w.startswith(('(', '+')) else w for w in sent])

<强>输出

['attachment', '1.', '=', 'EDT)', 'Details']

答案 1 :(得分:1)

您的代码无法正常运行,因为它正在构建2个列表;第一个包含以+(开头的内容,第二个包含不包含>>> sent = ['attachment', '(1.', '=', '+EDT)', 'Details'] >>> [ w[1:] if w.startswith(('(', '+')) else w for w in sent ] ['attachment', '1.', '=', 'EDT)', 'Details'] >>> import re >>> sent = ['attachment', '(1.', '=', '+EDT)', 'Details'] >>> [ re.sub(r'^[+(]', '', w) for w in sent ] ['attachment', '1.', '=','EDT)', 'Details'] 的内容。然后按顺序将它们连接起来。

您的代码已修复且正确使用条件表达式将会读取

^[+(]

然而,更好,更强大的选择是在这里使用re.sub

+

正则表达式 (匹配字符串的开头,后跟正好1 ''(;匹配的任何内容都替换为空字符串+

另一方面,如果你真的想删除所有前导.lstrip>>> sent = ['attachment', '(1.', '=', '+EDT)', 'Details'] >>> [ w.lstrip('+(') for w in sent ] ['attachment', '1.', '=', 'EDT)', 'Details'] 字符,无论多少,请使用+(++++((((foo

foo

这也会将mChooser=new DbxChooser(APP_KEY_DBX); 替换为appKeys= new AppKeyPair(APP_KEY,APP_SECRET); AndroidAuthSession session= new AndroidAuthSession(appKeys); mDBApi= new DropboxAPI<AndroidAuthSession>(session); mDBApi.getSession().startOAuth2Authentication(MainActivity.this); ,这可能是您想要的,也可能不是。

相关问题