在Python 3.6中,如果有换行符,则读取文件需要更长的时间.如果我有两个文件,一个有换行符,另一个没有换行符(否则它们有相同的文本),那么带换行符的文件大约需要100-200%的时间来读取.我提供了一个具体的例子.
sizeMB = 128
sizeKB = 1024 * sizeMB
with open(r'C:\temp\bigfile_one_line.txt', 'w') as f:
for i in range(sizeKB):
f.write('Hello World!\t'*73) # There are roughly 73 phrases in one KB
with open(r'C:\temp\bigfile_newlines.txt', 'w') as f:
for i in range(sizeKB):
f.write('Hello World!\n'*73)
Run Code Online (Sandbox Code Playgroud)
%%timeit
with open(r'C:\temp\bigfile_one_line.txt', 'r') as f:
text = f.read()
Run Code Online (Sandbox Code Playgroud)
1 loop, best of 3: 368 ms per loop
Run Code Online (Sandbox Code Playgroud)
%%timeit
with open(r'C:\temp\bigfile_newlines.txt', 'r') as f:
text = f.read()
Run Code Online (Sandbox Code Playgroud)
1 loop, best of 3: …Run Code Online (Sandbox Code Playgroud) 这是我想要创建的简化函数:
static List<object> GetAnonList(IEnumerable<string> names)
{
return names.Select(name => new { FirstName = name }).ToList();
}
Run Code Online (Sandbox Code Playgroud)
在该代码块中,我得到编译器错误:
错误CS0029无法将类型'System.Collections.Generic.List <>'隐式转换为'System.Collections.Generic.List'
在匿名类型的文档中,它表示匿名类型被视为类型对象.为什么不C#编译器返回List<object>的names.ToList()?
此外,为什么以下代码不会导致错误?如果List<<anonymous type: string FirstName>>无法转换为List<object>,那为什么可以转换为IEnumberable<object>?
static IEnumerable<object> GetAnonList(IEnumerable<string> names)
{
return names.Select(name => new { FirstName = name }).ToList();
}
Run Code Online (Sandbox Code Playgroud)