如何在数组中重复字符串



我想对数组中的字符串重复len(non_current_assets)次。所以我尝试了:

["",  "totalAssets", "total_non_current_assets" * len(non_current_assets), "totalAssets"]

但它回来了:

['',
'totalAssets',
'total_non_current_assetstotal_non_current_assetstotal_non_current_assetstotal_non_current_assetstotal_non_current_assets',
'totalAssets']

str放入list中,相乘,然后解压缩(使用*运算符(,即:

non_current_assets = (1, 2, 3, 4, 5)  # so len(non_current_assets) == 5, might be anything as long as supports len
lst = ["",  "totalAssets", *["total_non_current_assets"] * len(non_current_assets), "totalAssets"]
print(lst)

输出:

['', 'totalAssets', 'total_non_current_assets', 'total_non_current_assets', 'total_non_current_assets', 'total_non_current_assets', 'total_non_current_assets', 'totalAssets']

(在Python 3.7中测试(

这应该有效:

string_to_be_repeated = ["total_non_current_assets"]
needed_list = string_to_be_repeated * 3
list_to_appended = ["","totalAssets"]
list_to_appended.extend(needed_list)
print(list_to_appended)

您想要使用一个循环:

for x in range(len(non_current_assets)):
YOUR_ARRAY.append(”total_non_current_assets“)

您可以将itertools.repeat与拆包运算符*:一起使用

import itertools as it
["",  "totalAssets",
*it.repeat("total_non_current_assets", len(non_current_assets)),
"totalAssets"]

它使意图非常清晰,并保存了临时列表的创建(因此性能更好(。

In [1]: import itertools as it                                                                
In [2]: %timeit [0, 1, *[3]*1000, 4, 5]                                                       
6.51 µs ± 8.57 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
In [3]: %timeit [0, 1, *it.repeat(3, 1000), 4, 5]                                             
4.94 µs ± 73.6 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

相关内容

  • 没有找到相关文章

最新更新