python - 在 python 中使用列表理解扩展列表

标签 python list-comprehension

假设我有一个列表 项目 = ['abc', 'def', 'tre']。

现在我想在每个列表项之前插入一个标志。

例如,新列表 items2 应该是 ['-g', 'abc', '-g', 'def', '-g', 'tre']。

我可以阅读列表并在附加标志后附加每个列表,但我想开始以 python 方式进行操作。

我想到的是:

items2.extend(['-g', i] for i in items )

这给了我一个包含较小列表的列表:

items2 = [['-g', 'abc'], ['-g', 'def'], ['-g', 'tre']]

我理解这是因为这等同于说

items2.extend([ ... ] , [ ... ], [ ... ])

对此有什么想法吗?谢谢

最佳答案

[j for i in items for j in '-g', i]

关于python - 在 python 中使用列表理解扩展列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25537039/

相关文章:

python - matplotlib/seaborn : first and last row cut in half of heatmap plot

python - 检查元素是否在所有列表中一起出现?

python - 如何从字符串列表中删除单词列表

python - 列表理解和就地方法

python - pyspeedtest 找不到测试服务器

python - Numpy 的最小二乘没有残差

python - 计数是否在多个索引数据框中

python - Pandas 。 pd.read_csv KeyError :not in index error

python - 将列表理解表达式拆分为多行以更好地了解发生了什么?

python - 直接从列表理解中获取列表(没有嵌套列表)