繁体   English   中英

遍历一长串字符串并从原始列表构建新列表的最pythonic 方法是什么?

[英]What is the most pythonic way to iterate through a long list of strings and structure new lists from that original list?

我有一大串歌词。 列表中的每个元素都是一首歌曲,每首歌曲都有多行,其中一些行是标题,例如“[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)

参考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')]

请参阅此处的最佳答案: 了解切片符号

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM