简体   繁体   English

在不使用for循环的情况下从Python中的元组中删除特定字符?

[英]Remove specific characters from a tuple in Python without using for loop?

I have a tuple like this - ('app(le', 'orange', 'ban(ana') I want to remove bracket "(" from the words app(le and ban(ana. I have done it this way: 我有一个像这样的元组 - ('app(le','orange','ban(ana')我想删除括号“(”来自app(le和ban)(ana。我这样做了:

a=("App(le", "M(nago","banana")
b= list(a)
c = []
for x in b:
    x = x.replace("(","")
    c.append(x)
c=tuple(c)

This is giving me the desired output. 这给了我想要的输出。 But I want to do it without using for loop. 但是我想在不使用for循环的情况下这样做。

It sound like you want to use list comprehension! 听起来你想要使用列表理解!

Try c = tuple(x.replace('(','') for x in b) 尝试c = tuple(x.replace('(','') for x in b)

Here's some documentation on list comprehension! 这是关于列表理解的一些文档!

Using map & lambda 使用maplambda

Ex: 例如:

a= ("App(le", "M(nago","banana")
print( tuple(map(lambda x: x.replace("(",""), a)) )

Output: 输出:

('Apple', 'Mnago', 'banana')

Not very elegant, but it works with NO looping. 不是很优雅,但它适用于无循环。 While Rakesh and RMonaco's answers are probably better, this eliminates all loops. 虽然Rakesh和RMonaco的答案可能更好,但这消除了所有循环。

a = '/n/'.join(a).replace('(','').split('/n/')

FYI: I did a quick speed test of Rakesh, RMonaco, and my solutions. 仅供参考:我对Rakesh,RMonaco和我的解决方案进行了快速测试。 I doubt this will be an issue, but it was a point of interest for me so I will share. 我怀疑这将是一个问题,但这是我感兴趣的一点,所以我将分享。 After ten-million iterations (that's right, 10E6) in each solution. 在每个解决方案中经过一千万次迭代(正确,10E6)。 I think at this point it comes down to personal preference... 我认为在这一点上归结为个人偏好......

>>> Rakesh:   0:00:09.869150
    RMonaco:  0:00:06.967905
    tnknepp:  0:00:05.097533
>>> 

So we have a maximum difference of 0.47 microseconds per iteration. 因此,每次迭代的最大差异为0.47微秒。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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