小编pwa*_*ers的帖子

为什么没有换行符读取文件会更快?

在Python 3.6中,如果有换行符,则读取文件需要更长的时间.如果我有两个文件,一个有换行符,另一个没有换行符(否则它们有相同的文本),那么带换行符的文件大约需要100-200%的时间来读取.我提供了一个具体的例子.

步骤1:创建文件

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)

步骤#2:使用单行和时间性能读取文件

IPython的

%%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)

步骤#3:读取具有许多行和时间性能的文件

IPython的

%%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)

python file-io python-3.x

13
推荐指数
2
解决办法
495
查看次数

为什么IEnumerable的匿名类型不会在ToList()上返回List <object>?

这是我想要创建的简化函数:

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)

c# anonymous-types

5
推荐指数
1
解决办法
172
查看次数

标签 统计

anonymous-types ×1

c# ×1

file-io ×1

python ×1

python-3.x ×1