Python中如何将字符串有序分割后存入列表对应索引位置
Fixing Your List Assignment Issue
Let's break down what's happening with your code first:
- When you run
a=['fi lou you'.split()], thesplit()method already returns a list['fi', 'lou', 'you'], but you're wrapping that result inside another set of square brackets. So you end up with a list containing a list:[['fi', 'lou', 'you']]. That's why trying to accessa[0]gives you the whole sublist instead of the first string element.
The Solution
Simply remove the outer square brackets when assigning to a. Since split() directly outputs the list you need, you can assign it directly:
a = 'fi lou you'.split()
Let's Verify
If you run this corrected code, you'll get the behavior you want:
a[0]will be'fi'a[1]will be'lou'a[2]will be'you'
To confirm, you can print the value of a itself: it will be exactly ['fi', 'lou', 'you'], no nested lists involved!
内容的提问来源于stack exchange,提问作者David
相关产品推荐
相关产品推荐

