首页 > 解决方案 > 遍历一长串字符串并从该原始列表构造新列表的最pythonic方法是什么?

问题描述

我有一大串歌词。列表中的每个元素都是一首歌曲,每首歌曲都有多行,其中一些行是标题,例如“[Intro]”、“[Chorus]”等。我正在尝试遍历列表并创建新列表其中每个新列表都由某个部分中的所有行组成,例如“[Intro]”或“[Chorus]”。一旦我实现了这一点,我想创建一个 Pandas 数据框,其中每一行都是歌词,每一列是歌曲的那个部分(前奏、合唱、第 1 节等)。我是否以正确的方式思考这个问题?这是列表中 1 个元素的示例,以及我当前部分尝试迭代和存储的示例:

song_index_number = 0
line_index_in_song = 0

intro = []
bridge = []
verse1 = []
prechorus = []
chorus = []
verse2 = []
verse3 = []
verse4 = []
verse5 = []
outro = []

lyrics_by_song[30]
['[Intro]',
 '(Just the two of us, just the two of us)',
 'Baby, your dada loves you',
 "And I'ma always be here for you",
 '(Just the two of us, just the two of us)',
 'No matter what happens',
 "You're all I got in this world",
 '(Just the two of us, just the two of us)',
 "I would never give you up for nothin'",
 '(Just the two of us, just the two of us)',
 'Nobody in this world is ever gonna keep you from me',
 'I love you',
 '',
 '[Verse 1]',
 "C'mon Hai-Hai, we goin' to the beach",
 'Grab a couple of toys and let Dada strap you in the car seat',
 "Oh, where's Mama? She's takin' a little nap in the trunk",
 "Oh, that smell? Dada must've runned over a skunk",
 "Now, I know what you're thinkin', it's kind of late to go swimmin'",
 "But you know your Mama, she's one of those type of women",
 "That do crazy things, and if she don't get her way, she'll throw a fit",
 "Don't play with Dada's toy knife, honey, let go of it (No)",
 "And don't look so upset, why you actin' bashful?",
 "Don't you wanna help Dada build a sandcastle? (Yeah)",
 'And Mama said she wants to show you how far she can float',
 "And don't worry about that little boo-boo on her throat",
 "It's just a little scratch, it don't hurt",
 "Her was eatin' dinner while you were sweepin'",
 'And spilled ketchup on her shirt',
 "Mama's messy, ain't she? We'll let her wash off in the water",
 "And me and you can play by ourselves, can't we?",
 '',
 '[Chorus]',
 'Just the two of us, just the two of us',....

for line in lyrics_by_song:
    if lyrics_by_song == '[Intro]':
        intro.append(line)

标签: pythonpandaslistloopslogic

解决方案


参考python的文档:https ://docs.python.org/3/tutorial/datastructures.html#list-comprehensions

你也可以用这个

Intro = lyrics_by_song[lyrics_by_song.index('[Intro]'):lyrics_by_song.index('something_else')]

在此处查看最佳答案:了解切片表示法


推荐阅读