I am trying to get the value of the i sublist and then i'm indexing in order to find the 1st and 2nd values in that sublist.
However I cannot index by i, since it is a list. How can I achieve this output?
forSale = [[b, 50],[m,60],[t,90]]
if choice ==3:
i = len(forSale)
for i in forSale:
print forSale[i][0], ": ",forSale[i][1]
If you are trying to print the values of the sublist, then directly use i
, which points to the sublists in each iteration. Example -
forSale = [['b', 50],['m',60],['t',90]]
if choice ==3:
for i in forSale:
print '{0} : {1}'.format(i[0],i[1])
You can venture in to list comprehensions to solve this one.
Firstly, change your variable naming to this instead:
forSale
=> for_sale
Read up on pep8 for the style guide.
' '.join(["{}:{}".format(i[0],i[1]) for i in for_sale])
The ' '.join(
part will convert back to a string with a space between each word. The inside of the [ ]
is pretty much iterating over the array, grabbing the first and second index from the sublist and placing a :
between them.
If they have to be printed on individual lines then you are just gonna do this:
for i in for_sale:
print("{}:{}".format(i[0], i[1]))
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.