我需要在python中获取大文件(数十万行)的行数.记忆和时间方面最有效的方法是什么?
目前我这样做:
def file_len(fname):
with open(fname) as f:
for i, l in enumerate(f):
pass
return i + 1
Run Code Online (Sandbox Code Playgroud)
有可能做得更好吗?
阅读Python 3.1中的更改,我发现了一些......意外的:
sys.version_info元组现在是一个命名元组:
我之前从未听说过命名元组,我认为元素可以用数字(如元组和列表)或键(如dicts)索引.我从没想过他们可以两种方式编入索引.
因此,我的问题是:
**kwargs
在默认值方面,在Python中使用的正确方法是什么?
kwargs
返回字典,但设置默认值的最佳方法是什么,还是有一个?我应该只是作为字典访问它吗?使用get函数?
class ExampleClass:
def __init__(self, **kwargs):
self.val = kwargs['val']
self.val2 = kwargs.get('val2')
Run Code Online (Sandbox Code Playgroud)
一个简单的问题,但我找不到好的资源.人们在我看过的代码中采用不同的方式,并且很难知道要使用什么.
我想获取两个列表并找到两者中出现的值.
a = [1, 2, 3, 4, 5]
b = [9, 8, 7, 6, 5]
returnMatches(a, b)
Run Code Online (Sandbox Code Playgroud)
[5]
例如,会回来.
我想循环遍历文本文件的内容,并在某些行上进行搜索和替换,并将结果写回文件.我可以先将整个文件加载到内存中然后再写回来,但这可能不是最好的方法.
在以下代码中,最好的方法是什么?
f = open(file)
for line in f:
if line.contains('foo'):
newline = line.replace('foo', 'bar')
# how to write this newline back to the file
Run Code Online (Sandbox Code Playgroud) 当我想删除Cookie时,我试试
unset($_COOKIE['hello']);
Run Code Online (Sandbox Code Playgroud)
我在firefox的cookie浏览器中看到cookie仍然存在.我怎样才能真正删除cookie?
在for
循环遍历列表的Python 循环中,我们可以编写:
for item in list:
print item
Run Code Online (Sandbox Code Playgroud)
它整齐地遍历列表中的所有元素.有没有办法在循环中知道到目前为止我循环了多少次?例如,我想要一个列表,在我处理了十个元素后,我想用它们做一些事情.
我想到的替代方案将是这样的:
count=0
for item in list:
print item
count +=1
if count % 10 == 0:
print 'did ten'
Run Code Online (Sandbox Code Playgroud)
要么:
for count in range(0,len(list)):
print list[count]
if count % 10 == 0:
print 'did ten'
Run Code Online (Sandbox Code Playgroud)
到目前为止,是否有更好的方法(就像for item in list
)获得迭代次数?
python ×8
php ×2
string ×2
arrays ×1
cookies ×1
exec ×1
file ×1
file-io ×1
for-loop ×1
kwargs ×1
line-count ×1
list ×1
namedtuple ×1
text-files ×1
tuples ×1