Linking two items from two seperate lists together. python -
underneath have 2 lists have been imported text file. need way in able link lines together. if line1 printed randomly want line2 printed.
line1 = (file.readline()) line2 = (file.readline()) line3 = (file.readline()) line4 = (file.readline()) line5 = (file.readline()) line6 = (file.readline()) line7 = (file.readline()) line8 = (file.readline()) line9 = (file.readline()) line10 = (file.readline()) line11 = (file.readline()) line12 = (file.readline()) line13 = (file.readline()) line14 = (file.readline()) line15 = (file.readline()) line16 = (file.readline()) line17 = (file.readline()) line18 = (file.readline()) line19 = (file.readline()) line20 = (file.readline()) line21 = (file.readline()) line22 = (file.readline()) line23 = (file.readline()) line24 = (file.readline()) line25 = (file.readline()) line26 = (file.readline()) line27 = (file.readline()) line28 = (file.readline()) line29 = (file.readline()) line30 = (file.readline()) # creates empty list , fills definitions file defi = [] defi.append(line2) defi.append(line4) defi.append(line6) defi.append(line8) defi.append(line10) defi.append(line12) defi.append(line14) defi.append(line16) defi.append(line18) defi.append(line20) defi.append(line22) defi.append(line24) defi.append(line26) defi.append(line28) defi.append(line30) randdef = random.choice(defi) #chooses random lines list randdefi = random.choice(defi) # " " " " " " #creates empty list , fills keywords file key = [] key.append(line1) key.append(line3) key.append(line5) key.append(line7) key.append(line9) key.append(line11) key.append(line13) key.append(line15) key.append(line17) key.append(line19) key.append(line21) key.append(line23) key.append(line25) key.append(line27) key.append(line29) randkey = random.choice(key)
but need link lines in each list together. print together
just read whole file list, use slicing divide them 2 lists:
with open(filename, 'r') inputfile: lines = list(inputfile) key = lines[::2] # every second line defi = lines[1::2] # every second line, starting second
you pair them instead, straight file, little itertools
magic:
from itertools import tee, izip def pairwise(iterable): "s -> (s0,s1), (s1,s2), (s2, s3), ..." a, b = tee(iterable) next(b, none) return izip(a, b) open(filename, 'r') inputfile: key_def_pairs = list(pairwise(inputfile))
or turn straight dictionary:
with open(filename, 'r') inputfile: key_def_pairs = dict(pairwise(inputfile))
but need remove newlines first:
from itertools import imap open(filename, 'r') inputfile: key_def_pairs = dict(pairwise(imap(str.rstrip, inputfile)))