【问题标题】:Fastest way to replace a character in a list of lists替换列表列表中字符的最快方法
【发布时间】:2018-01-16 22:27:53
【问题描述】:

我有兴趣找到最快的方法来遍历列表列表并替换最内层列表中的字符。我正在从 Python 中的 CSV 文件生成列表列表。

Bing Ads API 向我发送了一份巨大的报告,但任何百分比都表示为“20.00%”而不是“20.00”。这意味着我无法将每一行按原样插入到我的数据库中,因为“20.00%”不会在 SQL Server 上转换为数字。

到目前为止,我的解决方案是在列表推导中使用列表推导。我编写了一个小脚本来测试与仅获取列表相比它的运行速度有多快,并且运行良好(大约是运行时间的 2 倍),但我很想知道是否有更快的方法。

注意:报告中的每条记录都有一个比率,因此也有一个百分比。所以每 记录必须访问一次,每个速率都必须访问一次(这就是 2 倍减速的原因吗?)

随着这些报告的规模不断扩大,我希望有一个更快的解决方案!

import time
import csv

def getRecords1():
   with open('report.csv', 'rU',encoding='utf-8-sig') as records:
       reader = csv.reader(records)
       while next(reader)[0]!='GregorianDate': #Skip all lines in header (the last row in header is column headers so the row containing 'GregorianDate' is the last to skip)
           next(reader)
       recordList = list(reader)
   return recordList

def getRecords2():
   with open('report.csv', 'rU',encoding='utf-8-sig') as records:
       reader = csv.reader(records)
       while next(reader)[0]!='GregorianDate': #Skip all lines in header (the last row in header is column headers so the row containing 'GregorianDate' is the last to skip)
           next(reader)
       recordList = list(reader)
   data = [[field.replace('%', '') for field in record] for record in recordList]
   return recordList

def getRecords3():
    data = []
    with open('c:\\Users\\sflynn\\Documents\\Google API Project\\Bing\\uploadBing\\reports\\report.csv', 'rU',encoding='utf-8-sig') as records:
        reader = csv.reader(records)
        while next(reader)[0]!='GregorianDate': #Skip all lines in header (the last row in header is column headers so the row containing 'GregorianDate' is the last to skip)
            next(reader)
        for row in reader:
            row[10] = row[10].replace('%','') 
            data+=[row]
    return data
        
def main():
    t0=time.time()
    for i in range(2000):
        getRecords1()
    t1=time.time()
    print("Get records normally takes " +str(t1-t0))

    t0=time.time()
    for i in range(2000):
        getRecords2()
    t1=time.time()
    print("Using nested list comprehension takes " +str(t1-t0))

    t0=time.time()
    for i in range(2000):
        getRecords3()
    t1=time.time()
    print("Modifying row as it's read takes " +str(t1-t0))



main()

编辑:我添加了第三个函数 getRecords3(),这是我见过的最快的实现。运行程序的输出如下:

获取记录一般需要30.61197066307068

使用嵌套列表理解需要 60.81756520271301

在读取时修改行需要 43.761850357055664

这意味着我们已将其从慢 2 倍的算法降低到大约慢 1.5 倍。谢谢大家!

【问题讨论】:

  • 所以数据是“矩形”? (每一行都有相同数量的单元格)?
  • 似乎您可以在阅读该行时删除“%”符号,而不是将该行放入记录列表中,然后必须再次遍历该列表才能删除“%”符号。
  • 您似乎将每个 '%' 替换为 ''?如果使用其他工具如 sed 会更快吗?
  • @WillemVanOnsem 是的,数据是矩形的,感谢澄清
  • @JimMischel 我现在要试一试,看看效果如何。

标签: python algorithm list


【解决方案1】:

您可能会检查就地内部列表修改是否比使用列表理解创建新列表更快。

所以,像

for field in record: for index in range(len(field)): range[index] = range[index].replace('%', '')

我们不能真正就地修改字符串,因为字符串是不可变的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-26
    • 1970-01-01
    • 1970-01-01
    • 2019-02-26
    • 1970-01-01
    相关资源
    最近更新 更多