为什么提出此问题呢 ?
我试图回答这个问题:检查所有值是否作为字典中的键存在,并提供比生成器理解更好的东西all(Python 循环,即使在理解中,与某些函数执行的隐式循环相比,也会减慢执行速度):
all(i in bar for i in foo)
Run Code Online (Sandbox Code Playgroud)
其中bar是一个字典,foo是一个列表,通过使用set.issubset(转换为setoffoo才能使用foo.issubset(bar)),并且没有成功击败解决all方案的时代(除非两个容器都转换为sets)。
我的问题:
来自以下文档set:
请注意,union()、intersection()、difference() 和 symmetry_difference()、issubset() 和 issuperset() 方法的非运算符版本将接受任何 iterable 作为参数。相反,基于运算符的对应部分需要设置其参数。这排除了像 set('abc') 和 'cbs' 这样容易出错的结构,有利于更具可读性的 set('abc').intersection('cbs')。
好的,但性能实际上取决于参数的类型,即使复杂性并不如此(Python 的复杂性 issubset()):
import timeit
foo = {i for i in range(1, 10000, 2)}
bar = foo - {400}
n=10000
x = timeit.timeit(setup="foo = {str(i) for i …Run Code Online (Sandbox Code Playgroud) 我注意到当我在列表理解中使用递归时会发生一些奇怪的事情.如果递归过深,解释器似乎空闲(我等了5分钟,什么都没发生).
为了这个问题,假设我想要展平嵌套列表(我没有 - 但它是一个简短的代码示例,说明了我遇到的问题):
def flatten(x):
if isinstance(x, list):
return [a for i in x for a in flatten(i)]
else:
return [x]
Run Code Online (Sandbox Code Playgroud)
使用辅助函数创建嵌套列表:
def wrap_in_lists(value, depth):
a = value
for _ in range(depth):
a = [a]
return a
Run Code Online (Sandbox Code Playgroud)
使用时效果很好:
>>> flatten(wrap_in_lists(1, 2**10))
[1]
Run Code Online (Sandbox Code Playgroud)
但是当我使用时它完全停止:
>>> flatten(wrap_in_lists(1, 2**11))
# Nothing happens, no exception, no result, no segfault, ...
Run Code Online (Sandbox Code Playgroud)
奇怪的是,使用生成器的类似方法不会显示此行为:
def flatten(l):
def inner(x):
for item in x:
if isinstance(item, list):
yield from inner(item)
else:
yield item
return list(inner(l))
>>> flatten(wrap_in_lists(1, …Run Code Online (Sandbox Code Playgroud) 我是一个十足的菜鸟,让 google 制作了我的第一个 python 脚本。
我正在打开 2 个文件并从列表 2 中删除列表 1。
修改 list2 以删除列表 1 中的内容后,我想按 IP 网络对列表进行排序。例如:
1.1.1.1/24
1.1.1.1/32
5.5.5.5/20
10.10.11.12/26
10.11.10.4/32
Run Code Online (Sandbox Code Playgroud)
目前正在排序
1.1.1.1/24
1.1.1.1/32
10.10.11.12/26
10.11.10.4/32
5.5.5.5/20
Run Code Online (Sandbox Code Playgroud)
代码:
import os
import sys
import random
import re
text_file = open("D:/file/update2.txt", "rt")
lines = str(text_file.readlines())
text_file.close()
ip_address = r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]
{1,3}/\d{1,2})'
foundip = re.findall( ip_address, lines )
text_file2 = open("D:/file/Block.txt", "rt")
lines2 = str(text_file2.readlines())
text_file2.close()
foundip2 = re.findall( ip_address, lines2 )
test =(list(set(foundip2) - set(foundip)))
items = sorted(test)
print (*items, sep …Run Code Online (Sandbox Code Playgroud) {m,n}?
Run Code Online (Sandbox Code Playgroud)
导致结果RE匹配先前RE的m到n个重复,并尝试匹配尽可能少的重复。这是前一个限定词的非贪婪版本。例如,在6个字符的字符串'aaaaaa'上,a {3,5}将匹配5个'a'字符,而a {3,5}?只能匹配3个字符。
但是,这似乎与以下实验相矛盾:
import re
regex = re.compile('(abc|d|abcde){1,2}?(e|f)')
regex.match('abcdef')
Run Code Online (Sandbox Code Playgroud)
...匹配“ abcde”。这必然涉及(abc | d | abcde)的2个重复,即“ abc”和“ d”。但是,有一个备选匹配候选者仅涉及1次(abc | d | abcde)重复,即“ abcde”。
我是在阅读文档,还是{m,n}?实际最小化匹配的字符数(或其他目标),而不是重复的次数?
我正在尝试从pandas DataFrame构建一个类.我只想向DataFrame类添加属性"name".但是下面的代码会产生递归最大深度误差.哪种方式可以使它工作?谢谢
import pandas as pd
class DatFrame(pd.DataFrame):
def __init__(self, name, data=None, index=None, columns=None,
dtype=None, copy=False):
self.name = name
pd.DataFrame.__init__(self, data=None, index=None,
columns=None, dtype=None, copy=False)
x = array([[9, 7, 5],
[7, 3, 1],
[8, 8, 3],
[7, 4, 3]])
cols = ['a', 'b', 'c']
index = ['D', 'E', 'F', 'G']
s = DatFrame('huy', x, index, cols)
Run Code Online (Sandbox Code Playgroud)
错误:RecursionError:调用Python对象时超出了最大递归深度
这个片段工作得很好
if True: print "just True"
if (True): print "(True)"
Run Code Online (Sandbox Code Playgroud)
正在研究循环,这些工作正常
for i in range(1, 3):
print i
i = 0
while i < 3: # without paranthesis
print i
i = i + 1
i = 0
while (i < 3): # with paranthesis
print i
i = i + 1
Run Code Online (Sandbox Code Playgroud)
当我尝试
for (i in range(1, 3)):
print i
Run Code Online (Sandbox Code Playgroud)
我收到错误"SyntaxError:invalid syntax"
我明白外面的括号是让循环变得疯狂(错误)但是我违反了哪一部分语法?它在while循环中运行良好
我有一个看起来像这样的元组列表:
[('a', 'b'), ('c', 'd'), (('e', 'f'), ('h', 'i'))]
Run Code Online (Sandbox Code Playgroud)
我想把它变成这个:
[('a', 'b'), ('c', 'd'), ('e', 'f'), ('h', 'i')]
Run Code Online (Sandbox Code Playgroud)
最恐怖的方式是什么?
我编写了不同的 python 代码来反转给定的字符串。但是,无法弄清楚其中哪一个是有效的。有人可以使用时间和空间复杂度指出这些算法之间的差异吗?
def reverse_1(s):
result = ""
for i in s :
result = i + result
return result
def reverse_2(s):
return s[::-1]
Run Code Online (Sandbox Code Playgroud)
有已经有一些解决方案在那里,但我无法找出时间和空间复杂度。我想知道需要多少空间s[::-1]?
python algorithm time-complexity space-complexity data-structures
我有一个json形式的字符串
{"1":"abc"abc"abc","2":"xyz"xyz"xyz"}
Run Code Online (Sandbox Code Playgroud)
但是,如果我想将其转换为json数据,我需要删除""之间的"",并获取如下所示的字符串
{"1":"abcabcabc","2":"xyzxyzxyz"}
Run Code Online (Sandbox Code Playgroud)
我尝试使用re.sub来做到这一点,但失败了.任何人都可以帮助我吗?我的脚本如下:
a='{"1":"abc"de"fg","2":"xyz"xyz"xyz"}'
r = re.compile(r'(?<!\:)(?<=.+)"|(?<!,)"|"(?!}|,)')
b = r.sub('', a)
print(b)
Run Code Online (Sandbox Code Playgroud)
当我运行脚本时,结果如下:
Traceback (most recent call last):
File "./_t1.py", line 5, in <module>
r = re.compile(r'(?<!\:)(?<=.+)"|(?<!,)"|"(?!}|,)')
File "/home/emc/ssd/anaconda3/lib/python3.6/re.py", line 233, in compile
return _compile(pattern, flags)
File "/home/emc/ssd/anaconda3/lib/python3.6/re.py", line 301, in _compile
p = sre_compile.compile(pattern, flags)
File "/home/emc/ssd/anaconda3/lib/python3.6/sre_compile.py", line 566, in compile
code = _code(p, flags)
File "/home/emc/ssd/anaconda3/lib/python3.6/sre_compile.py", line 551, in _code
_compile(code, p.data, flags)
File "/home/emc/ssd/anaconda3/lib/python3.6/sre_compile.py", line 187, in _compile
_compile(code, av, flags)
File "/home/emc/ssd/anaconda3/lib/python3.6/sre_compile.py", line 160, …Run Code Online (Sandbox Code Playgroud) 我有一系列文本帖子 (df['posttext'])。本系列中的每一行都是字符串。我想知道哪些包含问号。
当我尝试
df['posttext'].str.contains("?")
Run Code Online (Sandbox Code Playgroud)
我明白了:
error: nothing to repeat at position 0.
Run Code Online (Sandbox Code Playgroud) python ×10
algorithm ×1
cidr ×1
flatten ×1
inheritance ×1
jupyter ×1
list ×1
networking ×1
pandas ×1
parentheses ×1
performance ×1
python-2.6 ×1
python-3.x ×1
recursion ×1
regex ×1
set ×1
string ×1
syntax-error ×1