Python中如何获取列表的列表中字符串第n个元素及提取文本文件列表元素
Hey there! Let's walk through exactly how to handle your use case. First, let's formalize the data structure from your text file—it translates to a list of lists in Python, which looks like this:
data = [ [0, "we break dance not hearts by Short Stack is my ringtone.... i LOVE that !!!.....\n"], [1, "I want to write a . I think I will.\n"], [2, "@va_stress broke my twitter..\n"], [3, "\" "Y must people insist on talking about stupid politics on the comments of a bubblegum pop . Sorry\n"], [4, "aww great "Picture to burn"\n"] ]
1. Access the second element of each sub-list
In Python, indexing starts at 0, so the second element of any sub-list lives at index 1. You have a couple straightforward ways to do this:
Option 1: Loop through each sub-list (process elements one by one)
Perfect if you need to work with each element individually:
for sub_list in data: second_element = sub_list[1] # Do something with the element—like print it out print(second_element)
Option 2: Extract all second elements at once with a list comprehension
Use this to collect all the second elements into a new list for later use:
all_second_elements = [sub_list[1] for sub_list in data] print(all_second_elements)
2. Get the nth character from a string in the sub-list
Once you've grabbed the string (the second element of the sub-list), you use the same indexing logic—just add one more layer. Remember, string indexing also starts at 0, so:
- For the nth character (counting from 1), use index
n-1 - For the nth character (counting from 0), use index
n
Example: Get the 5th character (1-based) from every string
Always check if the string is long enough first to avoid an IndexError:
target_n = 5 # 1-based position, so we use index 4 for sub_list in data: text = sub_list[1] if len(text) >= target_n: nth_char = text[target_n - 1] print(f"5th character: {nth_char}") else: print("This string is too short to get the 5th character!")
Example: Get the 3rd character (0-based) from the first sub-list's string
first_text = data[0][1] third_char = first_text[2] print(third_char) # Outputs the space after "we" in the first string
Quick cheat sheet: data[i][j][k] breaks down to:
i: Index of the sub-list in the main listj: Index of the element inside the sub-listk: Index of the character inside the string element
内容的提问来源于stack exchange,提问作者Viral Patel

