Not sure why last print is off? Please see comments for specific question
john = ['john doe', 44, 32000]
jane = ['jane doe', 23, 12000]
people = [john, jane]
for p in people:
#===========================================================================
# p[0] prints "john doe" as expected
# p[0].split() prints ['john', 'doe'] as expected
# p[0].split()[0] prints "john" and "jane" as expected
#===========================================================================
for x in 开发者_C百科p[0].split():
print('--> ', x[0])
# prints "j","d" - not sure why
# expected "john" and "jane"
- p[0].split() returns a list of strings
- for x in... deals with each string in the list
- x[0] is therefore the first character in the string
you probably want to get rid of the subscript after 'x'.
Use it like this
for p in people:
#===========================================================================
# p[0] prints "john doe" as expected
# p[0].split() prints ['john', 'doe'] as expected
# p[0].split()[0] prints "john" and "jane" as expected
#===========================================================================
for x in p.split():
print('--> ', x)
As you said, p[0].split() gives you ['john', 'doe']. In your loop, x refers in turn to the elements of this list, "john" and "doe". x[0] refers to the first item in either of these-- the first character in the string.
精彩评论