如果列表中字符串的最后一个字符是“ - ”,则将其移动到字符串

时间:2018-04-17 09:19:10

标签: python string list split

我已拆分字符串以产生以下内容:

Transaction = ['03/29/18', '16,545,275.32-', '8,309,931.13-', '24,855,206.45-', '2.18', '1,505.11']

如何检查列表中的每个字符串以确定它是否以“ - ”结尾,并且是否将其移动到字符串的前面?输出应该类似于:

Transaction = ['03/29/18', '-16,545,275.32', '-8,309,931.13', '-24,855,206.45', '2.18', '1,505.11']

1 个答案:

答案 0 :(得分:2)

这是一个包含列表理解的单行程序:

>>> Transaction = ['03/29/18', '16,545,275.32-', '8,309,931.13-', '24,855,206.45-', '2.18', '1,505.11']

>>> ['-' + i[:-1] if i[-1] is '-' else i for i in Transaction]
['03/29/18', '-16,545,275.32', '-8,309,931.13', '-24,855,206.45', '2.18', '1,505.11']

说明:

这里i是迭代器,它迭代列表Transaction

中的每个元素

i[-1] - 获取字符串的最后一个字符(适用于非空字符串)

i[:-1] - 从起始元素到最后一个字符的切片字符串(不包括最后一个字符)

i[-1] is '-'

相比,

python更快地评估表达式i.endswith('-')

In [2]: %timeit ['-' + i[:-1] if i[-1] is '-' else i for i in Transaction]
950 ns ± 7.8 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [3]: %timeit ['-' + i[:-1] if i.endswith('-') else i for i in Transaction]
1.52 µs ± 10.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [4]: %timeit ['-' + i[:-1] if i[-1] == '-' else i for i in Transaction]
1.1 µs ± 4.79 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)