Python遍历列表并将项目重新拆分为列表

时间:2018-02-14 19:11:05

标签: python python-3.x list split

我有一个列表,其中包含我想要再次拆分的项目,并在列表中添加新项目。例如,给出以下列表:

{{ usr.nom }}

我想采取“大声朗读&激励反击”以及“走出这个世界>计划”项目并将其拆分为“>”并将“大声”,“激励反击”,“走出这个世界”和“计划”作为列表中的单独项目。

我尝试使用下面的代码,但它不起作用:

pre_songs = ['Totem', 'One, Two, Three', 'Rent', 'Vapors', 'Get Loud > Inspire Strikes Back', 
             'Enceladus', 'Moon Socket', 'Out of This World > Scheme', 'Walk to the Light', 
             'When The Dust Settles', 'Click Lang Echo']

4 个答案:

答案 0 :(得分:2)

使用extend

pre_setlist = []
for song in pre_songs:
    pre_setlist.extend([x.strip() for x in song.split('>')])

如果在>

之前和之后总是有一个空格,则更短
pre_setlist = []
for song in pre_songs:
    pre_setlist.extend(song.split(' > '))

带有示例列表的两个版本的结果:

>>> pre_setlist
['Totem',
 'One, Two, Three',
 'Rent',
 'Vapors',
 'Get Loud',
 'Inspire Strikes Back',
 'Enceladus',
 'Moon Socket',
 'Out of This World',
 'Scheme',
 'Walk to the Light',
 'When The Dust Settles',
 'Click Lang Echo']

答案 1 :(得分:1)

这是一种方式。

from itertools import chain

pre_setlist = []

for song in pre_songs:
    if '>' in song:
        pre_setlist.append(song.split(' > '))
    else:
        pre_setlist.append([song])

list(chain.from_iterable(pre_setlist))

# ['Totem', 'One, Two, Three', 'Rent', 'Vapors', 'Get Loud',
#  'Inspire Strikes Back', 'Enceladus', 'Moon Socket',
#  'Out of This World', 'Scheme', 'Walk to the Light',
#  'When The Dust Settles', 'Click Lang Echo']

这可以更简洁地写成列表理解:

from itertools import chain

pre_setlist = [[song] if '>' not in song \
               else song.split(' > ') for song in pre_songs]

list(chain.from_iterable(pre_setlist))

答案 2 :(得分:0)

你可以试试这个:

pre_songs = ['Totem', 'One, Two, Three', 'Rent', 'Vapors', 'Get Loud > Inspire Strikes Back', 
         'Enceladus', 'Moon Socket', 'Out of This World > Scheme', 'Walk to the Light', 
         'When The Dust Settles', 'Click Lang Echo']
final_songs = [i for b in [c.split(' > ') for c in pre_songs] for i in b]

输出:

['Totem', 'One, Two, Three', 'Rent', 'Vapors', 'Get Loud', 'Inspire Strikes Back', 'Enceladus', 'Moon Socket', 'Out of This World', 'Scheme', 'Walk to the Light', 'When The Dust Settles', 'Click Lang Echo']

答案 3 :(得分:0)

package com.xy.xy

import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.content_home_page)

}

你需要改变2件事

  1. for song in pre_songs: if '>' in song: pre_setlist.extend(song.split('>')) else: pre_setlist.append(song) 代替'>' in song
  2. 使用song.contains('>')代替extend,因为append会为您提供回复列表