简体   繁体   中英

How to split a python string based on indices?

I need to iterate through a list and for each element in that list, create two sublists: a sublist of the 2 elements before my current element, and a sublist of the 2 elements after.

for word in line.split():
\\ create sublist of the two words before word
\\ create sublist of the two words after word

I am not sure how to do this and would appreciate help. I know that you can generally do list[:5] but I'm not sure how to pick elements in relation to your current index.

You can use enumerate() to iterate over both the index and the element, then use slicing.

words = line.split()
for i, word in enumerate(words):
    print("word:", word)
    print("before:", words[i-2:i])
    print("after:", words[i+1:i+3])

Output:

word: I
before: []
after: ['would', 'like']
word: would
before: ['I']
after: ['like', 'a']
word: like
before: ['I', 'would']
after: ['a', 'hamburger']
word: a
before: ['would', 'like']
after: ['hamburger']
word: hamburger
before: ['like', 'a']
after: []

i think something like this is what you are looking for

line = "I would like a hamburger"
lst = line.split()
for index, word in enumerate(lst):
    print(lst[index-2:index],lst[index+1:index+3])

To look through each item in a list, simply do:

list = ['red', 'blue']
for item in range(len(list)):
    print(list[item])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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