繁体   English   中英

从一个文件复制到另一个文件并配对 python

[英]Copying from one file to another file and pairing in python

我有一个文件(比如 file.txt),它看起来像:

A,B,C,32
D,E,F,65
G,H,I,76
J,K,L,98
M,N,O,55
J,K,L,98
S,T,U,46
G,H,I,76

现在有 8 行,所以我想做 4 对。 第一次需要 2 行时,它将采用row with the highest 4th column value的行, 2nd row can be anyone from the remaining 7 rowsself pairing is not allowed 这意味着[(J,K,L,98),(J,K,L,98)]不能是一对。 假设在第一次迭代中它已将[(J,K,L,98),(S,T,U,46)]作为一对,那么在下一次迭代中将有 6 行中的 rest 行参与。

以下是我的尝试:

from random import choice   
file_name = 'file.txt'
fp = open(file_name)
val = []
for line in fp.readlines():
    val.append(line.replace("\n","").split(","))
    
val = sorted(val, key=lambda x: x[-1], reverse=True)

item_list = []
for i in val:
    i = list(map(str, i))
    s = ','.join(i).replace("\n","")
    item_list.append(s)
print(*item_list,sep='\n')

list1=[]   
for i in val:
    list1.append(i[-1])
print(list1)
p=max(list1)
print(max(list1))

final_list=[]
for i in val:
    if(i[-1]==p):
        final_list.append(i) 
    elif(i[-1]==choice(list1)):
        final_list.append(i)
        
        
print(final_list)

请帮帮我。

我对这个问题的解释是,你需要从文件(表)中取出一行,在第 4 个标记中具有最高数值。 然后你想随机取另一行并将其变成一对(元组列表)。 关键规则是任何对都不能有相等的元组。 我建议:

from random import choice

# handles each row from the file creating an appropriately structured tuple
def mfunc(s):
    t = s.strip().split(',')
    t[-1] = int(t[-1])
    return tuple(t)

# selects a random tuple from the given list ensuring that the selection cannot match the reference tuple
def gar(lst, ref=None):
    rv = choice([e for e in lst if e != ref]) if ref else choice(lst)
    lst.remove(rv)
    return rv

with open('file.txt') as infile:
    rows = sorted(list(map(mfunc, infile.readlines())), key=lambda x: x[-1])
    output = []
    t = rows[-1] # get row with highest value
    rows.pop(-1) # then remove it
    output.append([t, gar(rows, t)])
    while len(rows) > 1:
        a = gar(rows)
        output.append([a, gar(rows, a)])
    print(output)

Output(示例):

[[('J', 'K', 'L', 98), ('M', 'N', 'O', 55)], [('S', 'T', 'U', 46), ('A', 'B', 'C', 32)], [('G', 'H', 'I', 76), ('D', 'E', 'F', 65)], [('G', 'H', 'I', 76), ('J', 'K', 'L', 98)]]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM