PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, May 13, 2022

[FIXED] How to append items in multiple lists having same index into their original lists?

 May 13, 2022     append, for-loop, list, python, random     No comments   

Issue

I have an arbitrary number of lists, 3 taken here for example. The lists will have the same number of items and I want to append the items having the same index into their original list. This has to be done with some probability.

import random

individuals = 6
lists = 3

L1 = ['A', 'A', 'A', 'A', 'a', 'a']
L2 = ['B', 'B', 'B', 'B', 'b', 'b']
L3 = ['C', 'C', 'C', 'C', 'c', 'c']

for i in range(1, lists+1):
    for j in range(0, 6): 
      if random.random() <= 0.8:  
        ((eval(f'L{i}'))).append((eval(f'L{i}{[j]}')))
      else:
        pass

for i in range(1, lists+1):
    print(eval(f'L{i}'))

What I want is that L1[0], L2[0] and L3[0] be appended into their original list if they satisfy a probability. Then we do the same for L1[0], L2[1] and L3[2] and so on until we run out of the original items(6 in this example). If the probability is not satisfied, all items having the same index will not get appended.

The current result is giving me unequal sized lists at the end. The lists should be equal-sized as what I need is either all lists get appended at once or they don't.

Current result:

['A', 'A', 'A', 'A', 'a', 'a', 'A', 'A', 'a', 'a']
['B', 'B', 'B', 'b', 'b', 'b', 'B', 'B', 'B', 'b', 'b']
['C', 'C', 'C', 'c', 'c', 'c', 'C', 'C', 'C', 'c', 'c']

Solution

IIUC, you only need to reverse the order of the two for loops:

import random

individuals = 6
lists = 3

L1 = ['A', 'A', 'A', 'A', 'a', 'a']
L2 = ['B', 'B', 'B', 'B', 'b', 'b']
L3 = ['C', 'C', 'C', 'C', 'c', 'c']

for j in range(0, 6): 
    p = random.random()             # Random probability (same for all lists)
    if p <= 0.8:
        for i in range(1, lists+1): # all list get appended
            ((eval(f'L{i}'))).append((eval(f'L{i}{[j]}')))

for i in range(1, lists+1):
    print(eval(f'L{i}'))

Output

['A', 'A', 'A', 'A', 'a', 'a', 'A', 'A', 'A', 'a', 'a']
['B', 'B', 'B', 'B', 'b', 'b', 'B', 'B', 'B', 'b', 'b']
['C', 'C', 'C', 'C', 'c', 'c', 'C', 'C', 'C', 'c', 'c']
​


Answered By - DarrylG
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing