0

I have a 30 n random sample from a list which I write to a file.

I would rather like to tag the lines that went to the sample by writing in the end "in_sample" or "not_in_sample".

Now it looks like this:

mysample=random.sample(list, 30)
for i in mysample:
    out.write("%s\n" % (i))

I only write out lines from the sample but I would want the file to look like this:

line 1 in_sample

line 2 not_in_sample

line 3 in_sample

line 4 not_in_sample

The file looked the same before but without the last column.

Am I clear?

4 Answers 4

1

One way to do that is to sample on your list indexes instead of on its content.

For example, if your list is called lst:

indexes_samples = sorted(random.sample(range(len(lst)), 30))

for i in indexes_samples:
    lst[i]  # do what you want

Or maybe I think you might want to do something like:

idx = sorted(random.sample(range(len(lst)), 30))

j = 0
for i,num in enumerate(lst):
    if j <= len(idx) and i == idx[j]:
        msg = 'line {} in sample'
        j += 1
    else:
        msg = 'line {} not in sample'

    print(msg.format(num))   # out.write() or whatever
Sign up to request clarification or add additional context in comments.

1 Comment

@AWE: You're welcome! I restored those 2 lines from the old edit :)
1
my_sample = set(random.sample(my_list, 30))
for i, item in enumerate(my_list, 1):
    out.write('line {0} {1}\n'.format(i, ('not_in_sample', 'in_sample')[item in my_sample]))

Comments

1
mysample=random.sample(list, 30)
for i in range(1:31)
    if i in mysample:
        out.write("line %s\n in_sample" % (i))
    else:
        out.write("line %s\n not_in_sample" % (i))

Comments

0

Put your samples in a set, iterate from 1 to your maximum population value, and use containment testing to see if the current iteration is in the set.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.