将列表分为多个列表-取决于元素索引

时间:2019-11-08 16:02:38

标签: python python-3.x

我有一个包含4个元素的列表(元素的数量是动态的)。每个元素包含由不同语言组成的5个短语/句子的字符串,并用';'分隔分母。语言如下:ENG,FRE,GER,SPA,ITA。短语始终按此顺序出现在列表中的每个元素内。我现在正尝试从整个列表中按自己的语言列表提取这些短语。

我设法使用分隔符和 我尝试将此列表转换为字符串,然后使用字符串切片来获取结果,但是我无法找出使用代码编写结果的方式。

toJSON() { // * custom object to write to the .persistance file
    return {
      taskData: this.taskData,
      _handler: this._handler,
      _timer: this._timer, // TODO: store the clock time and reload timeout properly
      machineState: this.machineState,
    };
  }

这是原始的未更改列表:

list2 = combinedList .split(';')

hi = list2[0:2]
print(hi)
for element in range(0, len(list2)):
    print (list2[element])

我希望结果是:

combinedList = [
'40% Football;40% Football;40% Fuball;40% Futbol;40% Calcio;',
'30% Basketball;30% Basketball;30% Basketball;30% Baloncesto;30% Pallacanestro;',
'20% Baseball;20% Base-Ball;20% Baseball;20% Béisbol;',
'10% Rugby;10% Le Rugby;10% Rugby;10% Rugby;10% Rugby;'
']

1 个答案:

答案 0 :(得分:2)

您可以在列表理解中拆分字符串并使用zip

list(zip(*[i.split(';') for i in combinedList]))

[('40% Football', '30% Basketball', '20% Baseball', '10% Rugby'),
 ('40% Football', '30% Basketball', '20% Base-Ball', '10% Le Rugby'),
 ('40% Fuball', '30% Basketball', '20% Baseball', '10% Rugby'),
 ('40% Futbol', '30% Baloncesto', '20% Béisbol', '10% Rugby'),
 ('40% Calcio', '30% Pallacanestro', '', '10% Rugby')]