0

Underneath i have two lists which have been imported from a text file. I need a way in which to be able to link the lines together. so say if line1 is printed randomly I want line2 to be 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 an empty list and fills it with all the definitions from the 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 from the list 
randdefi = random.choice(defi) # "       "      "     "   "   "

#creates an empty list and fills it with all the keywords from the 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 i need to link certain lines in each list together. so they print together

4

1 回答 1

1

只需将整个文件读入一个列表,然后使用切片将它们分成两个列表:

with open(filename, 'r') as inputfile:
    lines = list(inputfile)

key = lines[::2]   # every second line
defi = lines[1::2] # every second line, starting with the second

您可以直接从文件中将它们配对,使用一点itertools魔法:

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)

with open(filename, 'r') as inputfile:
    key_def_pairs = list(pairwise(inputfile))

或者直接把它变成字典:

with open(filename, 'r') as inputfile:
    key_def_pairs = dict(pairwise(inputfile))

但您可能需要先删除换行符:

from itertools import imap

with open(filename, 'r') as inputfile:
    key_def_pairs = dict(pairwise(imap(str.rstrip, inputfile)))
于 2013-04-25T11:17:28.607 回答