簡體   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