Python 将分割值存储到单独的列表中
我想把这个列表分成两个不同的列表。我看到的水果的图案是数字Python 将分割值存储到单独的列表中,python,Python,我想把这个列表分成两个不同的列表。我看到的水果的图案是数字1。后面总是跟水果,而动物被放在空格之间,除了最后一个 text = ['1.banana dog 2.apple cat 3.grape tiger 4.orange snake', '1.watermelon hamster 2.pineapple fox 3.coconut lizard'] 输出将如下所示 fruit1 ['banana apple grape orange'] fruit2 ['watermelon pinea
1。
后面总是跟水果,而动物被放在空格之间,除了最后一个
text = ['1.banana dog 2.apple cat 3.grape tiger 4.orange snake', '1.watermelon hamster 2.pineapple fox 3.coconut lizard']
输出将如下所示
fruit1
['banana apple grape orange']
fruit2
['watermelon pineapple coconut']
animal
['dog cat tiger snake']
animal2
['hamster fox lizard']
有没有更简单的技巧可以让输出看起来像上面那样?您可以使用定期采样列表和
map()
:
text = ['1.banana dog 2.apple cat 3.grape tiger 4.orange snake']
textlist = text[0].split()
fruitlist = []
animallist = []
for word in textlist:
if "." in word:
fruitlist.append(word.split(".")[1])
else:
animallist.append(word)
fruit = " ".join(fruitlist)
animal= " ".join(animallist)
text=['1.香蕉狗2.苹果猫3.葡萄虎4.橙蛇']
words=文本[0]。拆分()
水果=[''.join(列表(地图(lambda x:x[2:],单词[0:][::2]))]
动物=[''.join(单词[1::[::2])]
使用正则表达式查找相关部分
texts = ['1.banana dog 2.apple cat 3.grape tiger 4.orange snake', '1.watermelon hamster 2.pineapple fox 3.coconut lizard']
fruits = []
animals = []
for text in texts:
fruit, animal = zip(*re.findall('\d+\.(\S+)\s+(\S+)', text))
fruits.append(fruit)
animals.append(animal)
texts = ['1.banana dog 2.apple cat 3.grape tiger 4.orange snake', '1.watermelon hamster 2.pineapple fox 3.coconut lizard']
fruits = []
animals = []
for text in texts:
fruit, animal = zip(*re.findall('\d+\.(\S+)\s+(\S+)', text))
fruits.append(fruit)
animals.append(animal)