Create a random list from oldList and append without repeating - python

appreciate it if someone can answer this.
I have a list called as oldList which contains something like this:
oldList = ['a','b','c','d']
Then I use random.shuffle(oldList) to get a random list and append those into randomList.
How can I check if I run again random.shuffle(oldList), and if the randomize list is already being appended into randomList, that randomize list would not be selected or append into randomList.

The shuffle() function returns nothing, it modifies an object in-place as pointed out by juanpa.arrivillaga.
I suspect you are looking for the sample() function which returns a list of items in a random order. In other words, sample() chooses a random sample from a population without replacement (where each item in the population has an equal chance to be picked). In the following example k is the random sample length.
from random import sample
example_list = ['a','b','c','d']
example_list.extend(sample(population=example_list, k=4))
print(example_list)
The order of the last four items will change each time you run this but the result will look like the following:
['a', 'b', 'c', 'd', 'b', 'd', 'c', 'a']
In the above example I used extend() instead of append() because the sample function outputs a list. append() would output something like this:
['a', 'b', 'c', 'd', ['b', 'd', 'c', 'a']]

Related

Parsed information that I'm trying to use to update another list (Python via replit)

I'm starting with a "text-type" file that I'm parsing (line by line) into lists that I'm manipulating. I'm using the lists: inputs, gateInput, gateOutput, gateType, nodeLevel, and gateList to manipulate the data as I need it. Presently, all the information parsed out correctly and I'm currently at an impasse.
I'm taking from a list of lists (gateInput) and I want to compare the contents with (inputs) to see if all the gateInputs are inputs. If so, I'm wanting to update the nodeLevel to reflect as such.
def compareInputs(x):
count = 0
for l in x:
for i in inputs:
if l in i:
print(x)
#---------------------------------------
for (g,h) in zip(gateList,nodeLevel):
for (a,b) in zip(gateOutput,gateInput):
if g == a:
compareInputs(b)
The two for loops and an if are what I'm using to get to where I send the item (b) to the function compareInputs. In compareInputs, I'm able to get things to cycle through, but it compares (lets say 'a') to every item list. Lets say that the len(list) is 3. So it compares 'a' three times, then goes to 'b' 3 times and then 'c' three times.
What I'm attempting to see is if list is comprised of only elements from inputs = ['a', 'b', 'c']. I do understand that this is a lot. It's not easy for me. I have a lot of things working against me. Any help would be appreciated.
Me printing in my function was to see if I'm getting the correct information to where I need it, and I am. Just need help with how to compare it to get the answer I'm after.
sample data
['c']
['a', 'b', 'c']
['a', 'b', 'c']
['a', 'b', 'c']
["a'", 'b', 'c']
["a'", 'b', 'c']
['c']
['a', "b'"]
['a']
['b']
['a', 'b', "c'"]
['a', 'b', "c'"]
["b'", 'c']
['b', "c'"]
These would be the component 'l' that is taken from 'x'. 'x' being a list of lists.

Taking the 'product' of lists

Suppose that I am given a list of strings, e.g. list = ['a', 'b', 'c']. I am also given a list of 'continuation strings', e.g. continuations = ['d', 'f'], and I want to form a list of all possible sequences formed by combining the original list with a continuation letter. In this example, I want to obtain the list of lists: new_list = [['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'f']]. To do this, I tried
new_list = []
for element in continuations:
# Make a copy of the original list
copy = list
# Add a continuation letter to the original list
possible_sequence = copy.append(element)
# Add the new list to the list of lists
new_list.append(possible_sequence)
But this generates [None, None]... Can anyone explain what is wrong with my code?
# it is a bad practice to shadows built-in name, so I changed 'list' name to 'abc_list'
abc_list = ['a', 'b', 'c']
continuation = ['d', 'f']
print([abc_list + [x] for x in continuation])
Output: [['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'f']]
CODE
main_list = ['a', 'b', 'c']
continuations = ['d', 'f']
new_list = []
for element in continuations:
temp_list = main_list.copy()
temp_list.append(element)
new_list.append(temp_list)
print(new_list)
OUTPUT
[['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'f']]
Here's how I would do it.
create a list to store the possible sequences
iterate through the continuation list
copy the original list
append the continuation letter to the copied list
append the copied list to the possible list
def combine_list(list_, cont_list):
# create a list to store the possible sequences
possible_list = []
# iterate through the continuation list
for j in cont_list:
# copy the original list
l2 = list_.copy()
# append the continuation letter to the copied list
l2.append(j)
# append the copied list to the possible list
possible_list.append(l2)
return possible_list
l = ['a', 'b', 'c']
c = ['d', 'f']
print(combine_list(l, c))
Output:
[['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'f']]
Edit
What's wrong with your code?
If you want to copy a list you need to it with list.copy(). If you just do copy = list you are not creating a new list object. if you make changes in copy all changes will apply to list also.
The list.append(element) function does not return a list object it returns None that's why your result looks like this [None, None] you appended None twice.
In Python, append modifies the list it is called on and doesn't return anything (technically it returns None, which is why you ended up with a list full of None). That means that you cannot store the result of append in a variable.
my_list = []
foo = my_list.append(1)
print(foo) # Prints 'None' because that's all that append returns
print(my_list) # Prints '[1]' because the value got added to the original list by append
This is the big difference between lists and strings in Python that beginners sometimes get confused about. Strings are immutable which means they cannot be changed. So methods such as replace return a new string, because they cannot modify the original string. Lists, on the other hand, are mutable, meaning they can be modified. So methods on lists such as append or pop modify the list they are called on rather than returning a new one.
my_string = "Python"
# Needs to be stored in a new variable,
# the original string cannot be modified
new_string = my_string.replace("n", "k")
print(my_string) # Still the original value, Python
print(new_string) # The new modified value, Pythok
my_list = [1, 2]
my_list.append(3) # Modified the list itself, no need to store anything new
print(my_list) # [1, 2, 3]
Also, note that it is an extremely bad idea to call one of your lists list as list is a keyword in Python. (It is used to construct new lists, e.g. list(range(10)) creates a list [0, 1, ..., 9]).

How to make a n-dimention list with one dimention lists with a loop

I'm learning python and I have been trying to make an automatic list of lists. For example:
The next list, which I have to split to get a list of separated letters, and then join them again to make a two lists of separated letters
lists=[['a,b,c,h'],['d,e,f,g']]
print('list length', len(lists))
splited=[]
splited1=lists[0][0].split(',')
print(splited1) #['a', 'b', 'c', 'h']
splited2=lists[1][0].split(',')
print(splited2) #['d', 'e', 'f', 'g']
listcomb=[splited1,splited2]
print(listcomb) #[['a', 'b', 'c', 'h'], ['d', 'e', 'f', 'g']]
This is what I want to get, a list that have 2 lists, but in the case I have to get more lists inside that list i want to make it automatic with a for loop.
My try, but it didn't work
listcomb2=zip(splited1,splited2)
print(listcomb2)
sepcomb = list()
print(type(sepcomb))
for x in range(len(lists)):
sep=lists[x][0].split(',')
sepcomb[x]=[sep]
print(sepcomb)
I'm having problems with splitting the letters and then joining them in a new list. Pls help
Make some tweak in your code. As we can see lenght of sepcomb is 0 so use append method to avoid this problem. As sepcomb[x]=[sep] is is assignment to x-index but it x index doesn't exist so, it will raise error
change:
for x in range(len(lists)):
sep=lists[x][0].split(',')
sepcomb[x]=[sep]
to
for x in range(len(lists)):
sep=lists[x][0].split(',')
sepcomb.append(sep)
Method-2
sepcomb = list(i[0].split(',') for i in lists)
You can simply do the following:
final=[splinted1]+[splinted2]
Or a better way directly from the lists variable would be:
final=[value[0].split(',') for value in lists]
Here you go:
lists = [['a,b,c,h'],['d,e,f,g']]
listcomb = []
for each in lists:
splited = each[0].split(',')
listcomb.append(splited)
print(listcomb)

Creating a list that gives a specific value at even indexes and another value at odd indexes

I want to create a list say chelsea_fc that will populate the value "EPL Champions" in even indexes and "Manager Sacked" at odd indexes till a given range. (dont want to hard code the range)
I am getting confused as how to do it. Please help
Literally write it as you would say it!
>>> ['a' if i % 2 else 'b' for i in range(10)]
['b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a']
You can do this (or any other list that repeat itself) like this:
chelsea_fc = ['Manager Sacked', 'EPL Champions']*(range_of_choice/2)
print(chelsea_fc)

choosing random values but have each value chosen an exact number of times

i'm new to python.
I have a list of four values.
I need to choose random values from this list 32 times.
However, I need that each value be chosen exactly 8 times.
so far I used this:
import random
my_list=['a','b','c','d']
for i in range(1,33):
selection=random.choice(my_list)
print("{} selection: {}".format(i,selection))
This works - but how do I get it to give me each value exactly 8 times?
Thanks for helping.
I would build a list with the required elements in it, then shuffle it.
import random
my_list = ['a', 'b', 'c', 'd'] * 8
random.shuffle(my_list)
Now my_list contains 32 elements in random order, with each unique element appearing eight times.
You can first multiply your list 8 times
>>> result = my_list*8
Then random.shuffle that list and str.join it.
>>> random.shuffle(result)
>>> print(''.join(result))
aaabdddbcdbcbabadcccddabbacbaccd
In order to ensure that each value is selected at 8 times for each element in your list you're going to need a counter for each element. You'll need to keep track of how many times each element has been selected.
Every time that choice is letter is randomly selected increment its unique counter by 1. When you run your random selection again you'll need to check if that value has been selected 8 times already. If it has toss that selection and run the random selection again. Then you'll need to check and see if its randomly returned result has been selected 8 times already.
Write a nested for loop, in which the outer for loop runs 8 times, and the inner for loop runs 4 times for the list of numbers. then in the list remove the value each time the for loop runs.
for i in range(1,8):
my_list = ['a','b','c','d']
for j in range(1,4):
rand = randint(1,(5-j))
print(rand)
my_list.remove([rand])
this is how I would do it, may not be the most efficient method, but you get the idea.
Create copies of each element with the multiply operator and then use random.shuffle to randomise the list elements:
>>> import random
>>> timesToSelectValue=8
>>> my_list=['a','b','c','d']
>>> new_list=my_list*timesToSelectValue
>>> random.shuffle(new_list)
>>> print(new_list)
['d', 'b', 'd', 'a', 'c', 'b', 'b', 'a', 'b', 'd', 'd', 'b', 'c', 'b', 'a', 'b', 'c', 'd', 'd', 'c', 'a', 'a', 'b', 'c', 'a', 'c', 'd', 'c', 'd', 'c', 'a', 'a']
new_list is now in a random order and contains exactly 8 of each element in my_list:
>>> for i in my_list:
... print("count {}={}".format(i,new_list.count(i)))
...
count a=8
count b=8
count c=8
count d=8

Categories