我想确定给定的元组是否为其他元组列表的子集。
我有一个元组列表,例如:
list_of_fails = list([[(1,2,3)],
[(1,2,5)],
[(1,4,3)]])
我想确定给定的元组是否是这些元组中任何一个的子集,例如元组
(1,2)
这里的结果将是,是,否
当我的元组被列出时,我能够执行此操作,例如以下代码将产生我想要的内容:
list_of_fails = list([[1,2,3],
[1,2,5],
[1,4,3]])
for sublist in list_of_fails:
if (set([1, 2]).issubset(sublist) == True):
print("yes")
else: print("no")
但是,将每个嵌入的元组转换为列表似乎效率很低。有没有更有效的方法来检查这一点?
答案 0 :(得分:1)
您只需要更进一步。使用设置操作已经非常有效。
%%timeit
for sublist in list_of_fails:
for i in sublist:
if set((1, 2)).issubset(i):
print("yes")
else: print("no")
#Output:
yes
yes
no
363 µs ± 91.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
使用itertools.combinations:
%%timeit
l = list(combinations(range(1,6), 2))
for sublist in list_of_fails:
for i in sublist:
for j in l:
if set(j).issubset(i):
print(j, i, "yes")
else: print(j,i, "no")
#Output:
(1, 2) (1, 2, 3) yes
(1, 3) (1, 2, 3) yes
(1, 4) (1, 2, 3) no
(1, 5) (1, 2, 3) no
(2, 3) (1, 2, 3) yes
(2, 4) (1, 2, 3) no
(2, 5) (1, 2, 3) no
(3, 4) (1, 2, 3) no
..... and so on
23.8 ms ± 1.74 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)
紧凑而快速的列表理解:
%%timeit
[print(j, i,"yes") if set(j).issubset(i) else print(j, i, "no") for sublist in list_of_fails for i in sublist for j in l]
#Output:
(1, 2) (1, 2, 3) yes
(1, 3) (1, 2, 3) yes
(1, 4) (1, 2, 3) no
(1, 5) (1, 2, 3) no
(2, 3) (1, 2, 3) yes
(2, 4) (1, 2, 3) no
(2, 5) (1, 2, 3) no
...and so on
18.3 ms ± 1.94 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)
如您所见,列表理解解决方案既紧凑又最快。
答案 1 :(得分:0)
将元组转换为列表实际上并不是性能问题。我使用以下代码对此进行了快速测试:
import random
import time
t0 = time.time()
rs = []
for i in range(10000):
r1, r2 = random.randint(0, 10), random.randint(0, 10)
t = (r1, r2)
l = list(t)
rs.append(l)
t1 = time.time()
print(t1 - t0)
在第二轮中,我取消注释l = list(t)
行,并将rs.append(l)
更改为rs.append(t)
。我得到的结果是:
0.04108595848083496
0.037944793701171875
这就像2个元组上每10.000 list()
次调用的3ms。
我想说您的解决方案是最好的方法。
答案 2 :(得分:0)
# define your search path
$files = Get-ChildItem "./some_path"
for ($i=0; $i -lt $files.Count; $i++) {
# loop through files in search folder
$x=Select-String -Path $files[$i].FullName -Pattern "whatYouSearch"
# retrieve the info with the option Line
$out=$x.Line
# echo to output file (append)
$out >> result.csv
}