简体   繁体   English

如何仅打印列表的特定部分?

[英]How to print only a certain part of a list?

If I wanted to get a certain part of a list to print what would I have to do?如果我想获取列表的某个部分来打印我必须做什么?

Here is an example;这是一个例子; say that:比如说:

list = [DOG, CAT, LION, TIGER, CAT, DOG, LION, LION, TIGER]

and I want it to just print the instances where it starts with CAT and stops at TIGER.我希望它只打印从 CAT 开始到 TIGER 停止的实例。 So from the above list I want to add the first instance CAT, LION, TIGER to a list, and the second instance CAT, DOG, LION, LION, TIGER to another list.所以从上面的列表中,我想将第一个实例 CAT, LION, TIGER 添加到一个列表中,并将第二个实例 CAT, DOG, LION, LION, TIGER 添加到另一个列表中。 so there is going to be 2 lists where:所以会有 2 个列表,其中:

list1 = [CAT, LION]

and

list2 = [CAT, DOG, LION, LION]

So is there a way for me to split the list up to a certain point?那么有没有办法让我将列表拆分到某个点?

Using the algorithm recommended in the comments :使用评论中推荐算法

my_list = ['DOG', 'CAT', 'LION', 'TIGER', 'CAT', 'DOG', 'LION', 'LION', 'TIGER']

# get the indicies of each element 'CAT' from the list
cat_indicies = [i for i, x in enumerate(my_list) if x == "CAT"]

# list comprehension for all elements between first and second instance of 'CAT'
my_list1 = [my_list[i] for i in range(*cat_indicies)]

# list of all elements starting from second instance of 'CAT'
my_list2 = my_list[cat_indicies[-1]::]

print(my_list1)  # ['CAT', 'LION', 'TIGER']
print(my_list2)  # ['CAT', 'DOG', 'LION', 'LION', 'TIGER']

note the lists result from requirements mentioned in the question, and do not necessarily match the example lists suggested in the question请注意列表是由问题中提到的要求产生的,不一定与问题中建议的示例列表相匹配

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

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