如何用.format()和列表索引方法从给定列表提取内容输出目标文本?
实现思路
首先拆解两个列表的嵌套结构,定位到目标文本需要的四个值:
- 第一朵花
tulip:在flowers列表的第一层索引0的子列表中,索引位置为2,取值为flowers[0][2] - 第二朵花
rose:在上述子列表的索引1嵌套列表中,索引位置为1,取值为flowers[0][1][1] - 第一个颜色
blue:在colors列表索引1的元组中,索引位置为0,取值为colors[1][0] - 第二个颜色
green:在上述元组的索引1嵌套列表中,索引位置为1,取值为colors[1][1][1]
完整可运行代码
text = "My two favorite flowers are tulip and rose, two favorite colors are blue and green." flowers = [["jasmine", ["lavender", "rose"], "tulip"]] colors = ["red", ("blue", ["yellow", "green"]), "pink"] print("My two favorite flowers are {} and {}, two favorite colors are {} and {} ".format(flowers[0][2], flowers[0][1][1], colors[1][0], colors[1][1][1]))
运行验证
执行上述代码后,输出结果和给定的目标text完全一致。
内容的提问来源于stack exchange,提问作者danny carey
相关产品推荐
相关产品推荐

