Python 删除集合中包含特定字符的所有元素
我有一组由生成器生成的几千个素数:Python 删除集合中包含特定字符的所有元素,python,set,Python,Set,我有一组由生成器生成的几千个素数: primes = set(primegen()) = set([..., 89, 97, 101, 103, ...]) 有些素数中有一个零。我想摆脱他们。有没有办法一次完成这一切 目前,我正在移除元素,通过正则表达式匹配循环素数: import re zero = re.compile('.+0.+') while primes: p = str(primes.pop()) if zero.match(p): conti
primes = set(primegen()) = set([..., 89, 97, 101, 103, ...])
有些素数中有一个零。我想摆脱他们。有没有办法一次完成这一切
目前,我正在移除元素,通过正则表达式匹配循环素数:
import re
zero = re.compile('.+0.+')
while primes:
p = str(primes.pop())
if zero.match(p):
continue
# do other stuff
我认为这是最好的方法,但我很好奇我是否错了。你可以使用集合理解来过滤你现有的素数集合
primes = {p for p in primes if '0' not in str(p)}
总结并确定答复的时间:
前100000个素数。(使用timeit并每次复制素数集)
根
10个回路,最好为3个:29.6 ms每个回路
迈克
10个回路,最好为3个:38.9 ms每个回路
加勒特河
1000个回路,最好3个:963µs每个回路
卡斯拉姆夫
1个循环,3个循环中最好:6.65秒
你好
10个循环,最好是3个:69.4 ms每个循环您不需要将数字转换为字符串并使用正则表达式匹配其中的零(或者更好地使用
in
操作符进行成员资格检查),这是一项昂贵的操作,特别是在处理大型数据集时。您可以使用以下函数检测数字中是否有零,然后在集合中使用它来保留预期的数字:
>>> def zero_membership_checker(num):
... while num:
... if num%10 == 0:
... return True
... num = num / 10
... return False
...
>>> s = set([89, 97, 101, 103])
>>>
>>> {i for i in s if not zero_membership_checker(i)}
set([89, 97])
免责声明:我完全不知道您想用它做什么,也不知道它为什么有用。我只是假设您想从
素数
集中删除像101
和103
这样的数字,因为它们包含零位
你甚至不需要正则表达式。可以通过简单的列表理解来完成:
# assume that primes is defined
str_primes = map(str, primes)
filtered_str_primes = [p for p in primes if "0" not in p]
filtered_primes = map(int, primes)
可能更快,你应该测试两个
我不确定你的集合是否只是一个例子,或者你是否计划使用生成器生成一个可能无限的素数列表。在后一种情况下,您可以使用itertools
惰性地定义过滤后的序列(也就是说,In将仅在您请求时生成下一个元素,而不是使用整个列表):
等等,我忘了,这应该会产生相同的结果,但代码更少(为了完整性,我将保留旧的解决方案):
过滤器
也适用于此应用程序:
In [25]: primes = set([83, 89, 97, 101, 103])
In [26]: filter(lambda x: '0' not in str(x), primes)
Out[26]: [89, 83, 97]
这里有一些时间信息,供好奇的人参考
In [37]: %timeit filter(lambda x: '0' not in str(x), myList)
10 loops, best of 3: 23.7 ms per loop
In [38]: %timeit {p for p in myList if '0' not in str(p)}
10 loops, best of 3: 22 ms per loop
仅供参考,您不需要列表(p)部分<代码>如果p中的“0”将在不进行转换的情况下工作
import re
zero = re.compile('.+0.+')
while primes:
p = str(primes.pop())
if zero.match(p):
continue
# do other stuff
>>> def zero_membership_checker(num):
... while num:
... if num%10 == 0:
... return True
... num = num / 10
... return False
...
>>> s = set([89, 97, 101, 103])
>>>
>>> {i for i in s if not zero_membership_checker(i)}
set([89, 97])
# assume that primes is defined
str_primes = map(str, primes)
filtered_str_primes = [p for p in primes if "0" not in p]
filtered_primes = map(int, primes)
from itertools import imap, ifilter
filtered_primes = imap(int,
ifilter(lambda p: "0" not in p,
imap(str, primes)))
filteres_primes = (p for p in primes if "0" not in str(p))
In [25]: primes = set([83, 89, 97, 101, 103])
In [26]: filter(lambda x: '0' not in str(x), primes)
Out[26]: [89, 83, 97]
In [37]: %timeit filter(lambda x: '0' not in str(x), myList)
10 loops, best of 3: 23.7 ms per loop
In [38]: %timeit {p for p in myList if '0' not in str(p)}
10 loops, best of 3: 22 ms per loop