【问题标题】:updating tuple string and how to optimize my code更新元组字符串以及如何优化我的代码
【发布时间】:2018-08-20 13:54:12
【问题描述】:

我有一份这样的清单:

  [`('__label__c091cb93-c737-4a67-95d7-49feecc6456c', 0.5), ('__label__96693d45-4dec-4b66-a2e2-621329d64b92', 0.498047)]`

我想像这样替换元组元素字符串值:

'__label__c091cb93-c737-4a67-95d7-49feecc6456c'到'c091cb93-c737-4a67-95d7-49feecc6456c'

我试试这个:

l = [('__label__c091cb93-c737-4a67-95d7-49feecc6456c', 0.5), ('__label__96693d45-4dec-4b66-a2e2-621329d64b92', 0.498047)]
j = []
for x in l:
    for y in x:
        if type(y) == str:
            z = y.replace('__label__',"")



    j.append((z, x[1]))



print(j)

输出:

[('c091cb93-c737-4a67-95d7-49feecc6456c', 0.5), ('96693d45-4dec-4b66-a2e2-621329d64b92', 0.498047)]

如何以pythonic方式优化我的代码以及更新元组值的任何其他方式,因为元组是不可变的

【问题讨论】:

  • 某种形式的列表理解?通过使用它,我已经将单个函数的时间缩短了半秒。我无法对此进行测试,如果有错误,我很抱歉[(z,x[1]) for x in l for y in x if type(y) == str]

标签: python-3.x list tuples


【解决方案1】:

你是对的,元组在 Python 中是不可变的,但列表不是。因此,您应该能够就地更新列表l。 此外,看起来您已经知道要修改的元素的位置以及要删除的子字符串的位置,因此您可以避免一个循环和 replace 函数,该函数将再次遍历您的字符串。

for i in range(len(l)):
    the_tuple = l[i]
    if isinstance(the_tuple[0], str) and the_tuple[0].startswith('__label__'):
        l[i] = (the_tuple[0][len('__label__'):], the_tuple[1])
        # you can also replace "len('__label__')" by "8" to increase performances
        # but I think Python already optimizes it

【讨论】:

  • [len('label') - 1 :] remove -1 没问题 谢谢@gogz
【解决方案2】:

您可以使用地图功能:

data = [('__label__c091cb93-c737-4a67-95d7-49feecc6456c', 0.5), ('__label__96693d45-4dec-4b66-a2e2-621329d64b92', 0.498047)]
def f(row): return row[0].replace('__label__', ''), row[1]
print(list(map(f, data)))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-12
    • 1970-01-01
    • 2014-06-17
    • 2020-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多