Reputation: 637
I have multiple questions and have found myself quite lost in python.
Questions:
How do I compare three list? (would it be a similar to "for x in y")
Example:
list1 = [1,2,3]
list2 = [a,b,c]
list3 = [aa,bb,cc]
OUTPUT:
[1,a,aa] [2,b,bb] [3,c,cc]
I am working on creating a simulation for a race, 1=vehicle , a=driver , aa= sponsor I have been given a formula, odometer_miles = odometer_miles + speed * time and a cap of 500 miles before a winner is selected. I have come up with a skeleton:
import random
class Car():
def __init__(self):
self.__name = [A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T]
self.__sponsor = [aa,bb,cc,dd,ee,ff,gg,hh,ii,jj,kk,ll,mm,nn,oo,pp,qq,rr,ss,tt]
self.__vehicle = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
def __str__(self):
(when cap of 500 miles is reached)
print "winner", driver,sponsor,vehicle
def odometer(self):
speed = random.randrange(1, 180)
time = 60
odometer_miles = speed * time
def main():
main()
I posted the code looking for guidance, My question is; have I structured my code correctly in python to get me intended results. What guts would be the most proficient in this instance.
I am using Python-3.x
Upvotes: 1
Views: 97
Reputation: 52000
Given the three lists:
list1 = [1,2,3]
list2 = ['a','b','c']
list3 = ['aa','bb','cc']
The zip()
function (or preferably maybe izip()
) will combine them such as the first item of each list are grouped, then the second item, and so on:
>>> for item in zip(list1, list2, list3):
... print item
...
(1, 'a', 'aa')
(2, 'b', 'bb')
(3, 'c', 'cc')
# `izip` is more "memory efficient" (no a problem here thought)
>>> from itertools import izip
>>> for item in izip(list1, list2, list3):
... print item
...
(1, 'a', 'aa')
(2, 'b', 'bb')
(3, 'c', 'cc')
On the other hand, if you want all combinations containing one item of list1, one of list2 and so on, you will need product()
:
>>> from itertools import product
>>> for item in product(list1, list2, list3):
... print item
...
(1, 'a', 'aa')
(1, 'a', 'bb')
(1, 'a', 'cc')
(1, 'b', 'aa')
(1, 'b', 'bb')
(1, 'b', 'cc')
(1, 'c', 'aa')
(1, 'c', 'bb')
(1, 'c', 'cc')
(2, 'a', 'aa')
(2, 'a', 'bb')
(2, 'a', 'cc')
(2, 'b', 'aa')
(2, 'b', 'bb')
(2, 'b', 'cc')
(2, 'c', 'aa')
(2, 'c', 'bb')
(2, 'c', 'cc')
(3, 'a', 'aa')
(3, 'a', 'bb')
(3, 'a', 'cc')
(3, 'b', 'aa')
(3, 'b', 'bb')
(3, 'b', 'cc')
(3, 'c', 'aa')
(3, 'c', 'bb')
(3, 'c', 'cc')
This last one might be useful in your particular case, as it would allow you to simulate all possible combinations of drivers/vehicle/sponsor.
Upvotes: 2
Reputation: 1122232
You can re-combine multiple lists column-by-column with the zip()
function:
output = list(zip(list1, list2, list3))
If all you do is loop over each combination, use it directly in a loop:
for vehicle, driver, sponsor in zip(self.__vehicle, self.__name, self.__sponsor):
# do something with the three columns.
Upvotes: 3