Dear all,

I have two columns in a tab-delimited text file. I want to randomly generate a pair of entries from column1 and column2. Example -
Want to randomise following pairs so that each value will have different partner after randomisation. Actually I have a very big file with 5000 connections. i want to randomise the connections 100 times and take the average of all as the final. I have tried doing this but no clue :-/. sample file is attached.

234 one
238 thre
2 one
23 not
5 two
6 five
7 nine
7 ten

Recommended Answers

All 4 Replies

Work it, and post when you get stuck.

from random import choice

first_list = []
second_list = []

for item in open('sampleconnection.txt').readlines():
    first, second = item.split('\t')
    first_list.append(first)
    second_list.append(second.strip('\n'))

for i in range(len(first_list)):
    choices_list = range(len(first_list) - 1)
    choices_list.remove(i)
    print first_list[i], second_list[choice(choices_list)]

Cheers and Happy coding

Create 2 lists, one per column, and use the shuffle function of random on both,

Create 2 lists, one per column, and use the shuffle function of random on both,

One column randomization with shuffle should be enough, as reading order don't need maybe to randomize.

Thanks a lot dear all!
Worked I have modified it little a bit to get 10 fold!


Work it, and post when you get stuck.

from random import choice

first_list = []
second_list = []

for item in open('sampleconnection.txt').readlines():
    first, second = item.split('\t')
    first_list.append(first)
    second_list.append(second.strip('\n'))

for i in range(len(first_list)):
    choices_list = range(len(first_list) - 1)
    choices_list.remove(i)
    print first_list[i], second_list[choice(choices_list)]

Cheers and Happy coding

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.