将两个单独列表中的两个项目链接在一起。蟒蛇

时间:2013-04-25 11:15:36

标签: python list linker

下面我有两个已从文本文件导入的列表。我需要一种能够将线路连接在一起的方法。所以说如果随机打印line1我想要打印line2。

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)

但我需要将每个列表中的某些行链接在一起。所以他们一起打印

1 个答案:

答案 0 :(得分: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)))