我有一个csv DictReader对象(使用Python 3.1),但我想知道在迭代它之前阅读器中包含的行数/行数.如下......
myreader = csv.DictReader(open('myFile.csv', newline=''))
totalrows = ?
rowcount = 0
for row in myreader:
rowcount +=1
print("Row %d/%d" % (rowcount,totalrows))
Run Code Online (Sandbox Code Playgroud)
我知道我可以通过迭代读取器来获得总数,但是我无法运行'for'循环.我可以遍历阅读器的副本,但我找不到如何复制迭代器.
我也可以用
totalrows = len(open('myFile.csv').readlines())
Run Code Online (Sandbox Code Playgroud)
但这似乎是不必要的重新打开文件.如果可能的话,我宁愿从DictReader获取计数.
任何帮助,将不胜感激.
艾伦
Python的itertools实现了一个链迭代器,它基本上连接了许多不同的迭代器,以提供单个迭代器的所有东西.
C++中有类似的东西吗?快速浏览一下boost库并没有发现类似的东西,这对我来说非常令人惊讶.难以实现此功能吗?
我正在编写一个函数来确定字符串是否只包含字母数字字符和空格.我正在有效地测试它是否与正则表达式匹配^[[:alnum:] ]+$但不使用正则表达式.这是我到目前为止:
#include <algorithm>
static inline bool is_not_alnum_space(char c)
{
return !(isalpha(c) || isdigit(c) || (c == ' '));
}
bool string_is_valid(const std::string &str)
{
return find_if(str.begin(), str.end(), is_not_alnum_space) == str.end();
}
Run Code Online (Sandbox Code Playgroud)
是否有更好的解决方案或"更多C++"方式来做到这一点?
更新基于Lennart Regebro的回答
假设您遍历字典,有时需要删除元素.以下是非常有效的:
remove = []
for k, v in dict_.items():
if condition(k, v):
remove.append(k)
continue
# do other things you need to do in this loop
for k in remove:
del dict_[k]
Run Code Online (Sandbox Code Playgroud)
这里唯一的开销是构建要删除的键列表; 除非它与字典大小相比变大,否则不是问题.但是,这种方法需要一些额外的编码,所以它不是很受欢迎.
流行的词典理解方法:
dict_ = {k : v for k, v in dict_ if not condition(k, v)}
for k, v in dict_.items():
# do other things you need to do in this loop
Run Code Online (Sandbox Code Playgroud)
导致完整的字典副本,如果字典变大或经常调用包含函数,则存在愚蠢的性能损失的风险.
更好的方法是仅复制密钥而不是整个字典:
for k in list(dict_.keys()):
if condition(k, dict_[k]):
del dict_[k]
continue
# do …Run Code Online (Sandbox Code Playgroud) 我有一个名为Collectionstore 的类,它存储相同类型的对象.
Collection实现阵列接口:Iterator,ArrayAccess,SeekableIterator,和Countable.
我想将一个Collection对象作为数组参数传递给array_map函数.但这失败了,错误
PHP警告:array_map():参数#2应该是一个数组
我可以通过实现其他/更多接口来实现这一点,以便将Collection对象视为数组吗?
它是指定的,你可以在一个实例删除任何元素Set,同时采用迭代for..of和
?
正如标题所要求的那样.
我对双端队列的理解是它分配了"块".我没有看到如何分配更多的空间使迭代器无效,如果有的话,人们会认为deque的迭代器比矢量更有保证,而不是更少.
嗨,我有一个程序,处理很多这些向量的元素的向量和索引,我想知道:
uint和之间有区别吗?unsigned int int因为我读了一些人说编译器确实更有效地处理int值,但如果我使用int我将不得不总是检查负idxs这是痛苦.vectorx[idx]吗?ps软件将处理大数据流程,良好的性能是必须要求的
我如何编写一个Java迭代器(即需要next和hasNext方法),它采用二叉树的根,并按顺序迭代二叉树的节点?
iterator ×10
c++ ×5
python ×2
python-3.x ×2
stl ×2
algorithm ×1
array-map ×1
arrays ×1
binary-tree ×1
deque ×1
dictionary ×1
ecmascript-6 ×1
indexing ×1
int ×1
java ×1
javascript ×1
nodes ×1
php ×1
set ×1
string ×1
unsigned ×1
vector ×1