I want to randomly assign the three items from list into randlist but I also don't want the items to be assigned more than once
I tried to use a while loop that would pop the items randomly into randlist but it seems to be taking characters from the array item instead of the entire string.
from random import randint
list = ["car", "zonk1", "zonk2"]
randlist = []
x = 0
while x < 3:
randlist += list.pop(randint(0, len(list) - 1))
x += 1
door1 = randlist[0]
door2 = randlist[1]
door3 = randlist[2]
print (door1, door2, door3)
Result:
z o n
This line:
randlist += list.pop(randint(0, len(list) - 1))
extends the str object, character by character, into the list.
>>> mylist = []
>>> mylist += 'foo'
>>> mylist
['f', 'o', 'o']
You want to append what you are popping.
>>> mylist = []
>>> mylist.append('foo')
>>> mylist
['foo']
As an aside, you should use other functions in the random module instead of re-inventing the wheel. You want a random sample from your list:
>>> import random
>>> mylist = ["car", "zonk1", "zonk2"]
>>> random.sample(mylist, 3)
['zonk1', 'car', 'zonk2']
>>> random.sample(mylist, 3)
['zonk2', 'car', 'zonk1']
>>> random.sample(mylist, 3)
['car', 'zonk2', 'zonk1']
If you are willing to use numpy. Then the following code is slightly faster (and arguably neater) than for-looping:
import numpy as np
_list = ["car", "zonk1", "zonk2"]
idx = np.random.permutation(len(_list))
mylist = list(np.array(_list)[idx])
Example output:
>>> mylist
['zonk1', 'car', 'zonk2']
Related
How can i choose random multiple elements from list ? I looked it from internet but couldn't find anything.
words=["ar","aba","oto","bus"]
You could achieve that with random.sample():
from random import sample
words = ["ar", "aba", "oto", "bus"]
selected = sample(words, 2)
That would select 2 words randomly from the words list.
You can check Python docs for more details.
I think about that :
import random as rd
words=["ar","aba","oto","bus"]
random_words = [word for word in words if rd.random()>1/2]
You can adjust 1/2 by any value between 0 and 1 to approximate the percentage of words chosen in the initial list.
Use random
Here is example
random.choice
>>> import random
>>> words=["ar","aba","oto","bus"]
>>> print(random.choice(words))
ar
>>> print(random.choice(words))
ar
>>> print(random.choice(words))
oto
>>> print(random.choice(words))
aba
>>> print(random.choice(words))
ar
>>> print(random.choice(words))
bus
random.sample # sample takes one extra argument to pass a list with element is returned
>>> print(random.sample(words, 3))
['bus', 'ar', 'oto']
>>> print(random.sample(words, 3))
['ar', 'oto', 'aba']
>>> print(random.sample(words, 2))
['aba', 'bus']
>>> print(random.sample(words, 2))
['ar', 'aba']
>>> print(random.sample(words, 1))
['ar']
>>> print(random.sample(words, 1))
['ar']
>>> print(random.sample(words, 1))
['oto']
>>> print(random.sample(words, 1))
['bus']
You can use random library
Method 1 - random.choice()
from random import choice
words=["ar","aba","oto","bus"]
word = choice(words)
print(word)
Method 2 - Generate Random Index
from random import randint
words=["ar","aba","oto","bus"]
ind = randint(0, len(words)-1)
word = words[ind]
print(word)
Method 3 - Select Multiple Items
from random import choices
words=["ar","aba","oto","bus"]
selected = choices(words, k=2) # k is the elements count to select
print(selected)
I'm wondering if there is a way to check if any combination of more than two items from a list exists in another list?
list_1 = ['apple','soap','diet coke','banana','sweets','mash','fruit','veggies']
for string in lists:
strings = string.split()
print(strings)
SAMPLE OUTPUT for strings:
['today', 'i','bought','banana','but','forgot','soap', 'and','veggies']# this line should identify 'banana', 'soap' and 'veggies'
['maybe', 'there','are','more','sweets','left','later'] # this line should be ignored, because not more than 2 items of the list are in it
['food', 'shopping','is','boring','and','i','hate','mash','with','veggies']# this line should identify 'mash' and 'veggies'
I know that by using this piece of code, I can at least check if any of the elements appear in strings:
combinations = any(i in list_1 for i in strings)
You can use set intersection and check the resulting size:
s1 = set(list_1)
if len(s1.intersection(strings)) >= 2:
# do stuff
This will, however, not trigger if the same item occurs twice in strings which may or may not be what you desire. In that case, you could do something like:
if sum(s in s1 for s in strings) >= 2:
# do stuff
I was late apparently. This is basically schwobaseggl's solution wrapped as a function
mylist = ['apple','soap','diet coke','banana','sweets','mash','fruit','veggies']
mytest = ['today', 'i','bought','banana','but','forgot','soap', 'and','veggies']
def common_elements(mylist, mytest):
common_elements = list(set(mylist).intersection(mytest))
if len(common_elements)>2:
return common_elements
else:
pass
This should work:
string = ['today', 'i','bought','banana','but','forgot','soap', 'and','veggies']
list_1 = ['apple','soap','diet coke','banana','sweets','mash','fruit','veggies']
n = 0
inv = []
for i in string:
if i in list_1:
inv.append(i)
n += 1
if n >= 2:
print(inv)
or you can put it into a define and make yourself a function:
def check(string,list_1):
inv = []
for i in string:
if i in list_1:
inv.append(i)
if len(inv) >= 2:
return inv
else: return []
string = ['today', 'i','bought','banana','but','forgot','soap', 'and','veggies']
list_1 = ['apple','soap','diet coke','banana','sweets','mash','fruit','veggies']
print(check(string,list_1))
You can try this "hard-coded" way too
list1=['apple','soap','diet coke','banana','sweets','mash','fruit','veggies']
list2 = ['today', 'i','bought','banana','but','forgot','soap', 'and','veggies']
def check(list_1,list_2) :
common = list()
for i in list_1 :
if i in list_2 :
common.append(i)
if len(common) >=2 :
return common
else :
return "Less than two items are common"
try = check(list_1,list_2)
If I am not wrong, you want to find out that 2 lists have more than 2 same element?
def intersection(list_one, list_two):
intersection = set(list_one) & set(list_two)
if len(list(intersection)) > 1:
print(list(intersection))
return False
a = [1, 2, 3, 4]
b = [1, 8, 9, 10]
c = [1, 2, 5, 6]
intersection(a, b) # return False
intersection(a, c) # return [1, 2]
For example, I have the following list.
list=['abc', 'def','ghi','jkl','mn']
I want to make a new list as:
newList=['adgjm','behkn','cfil']
picking every first character of each element forming a new string then appending into the new list, and then with the second character of every element and so on:
Thanks for the help.
One way is zipping the strings in the list, which will interleave the characters from each string in the specified fashion, and join them back with str.join:
l = ['abc', 'def','ghi','jkl']
list(map(''.join, zip(*l)))
# ['adgj', 'behk', 'cfil']
For strings with different length, use zip_longest, and fill with an empty string:
from itertools import zip_longest
l = ['abcZ', 'def','ghi','jkl']
list(map(''.join, zip_longest(*l, fillvalue='')))
# ['adgj', 'behk', 'cfil', 'Z']
You can try this way:
>>> list1 =['abc', 'def','ghi','jkl']
>>> newlist = []
>>> for args in zip(*list1):
... newlist.append(''.join(args))
...
>>> newlist
['adgj', 'behk', 'cfil']
Or using list comprehension:
>>> newlist = [''.join(args) for args in zip(*list1)]
>>> newlist
['adgj', 'behk', 'cfil']
You can try this:
list=['abc', 'def','ghi','jkl']
n = len(list[0])
newList = []
i = 0
for i in range(n):
newword = ''
for word in list:
newword += word[i]
newList.append(newword)
print(newList)
I have a list of strings:
a = ['book','book','cards','book','foo','foo','computer']
I want to return anything in this list that's x > 2
Final output:
a = ['book','book','book']
I'm not quite sure how to approach this. But here's two methods I had in mind:
Approach One:
I've created a dictionary to count the number of times an item appears:
a = ['book','book','cards','book','foo','foo','computer']
import collections
def update_item_counts(item_counts, itemset):
for a in itemset:
item_counts[a] +=1
test = defaultdict(int)
update_item_counts(test, a)
print(test)
Out: defaultdict(<class 'int'>, {'book': 3, 'cards': 1, 'foo': 2, 'computer': 1})
I want to filter out the list with this dictionary but I'm not sure how to do that.
Approach two:
I tried to write a list comprehension but it doesn't seem to work:
res = [k for k in a if a.count > 2 in k]
A very barebone answer is that you should replace a.count by a.count(k) in your second solution.
Although, do not attempt to use list.count for this, as this will traverse the list for each item. Instead count occurences first with collections.Counter. This has the advantage of traversing the list only once.
from collections import Counter
from itertools import repeat
a = ['book','book','cards','book','foo','foo','computer']
count = Counter(a)
output = [word for item, n in count.items() if n > 2 for word in repeat(item, n)]
print(output) # ['book', 'book', 'book']
Note that the list comprehension is equivalent to the loop below.
output = []
for item, n in count.items():
if n > 2:
output.extend(repeat(item, n))
Try this:
a_list = ['book','book','cards','book','foo','foo','computer']
b_list = []
for a in a_list:
if a_list.count(a) > 2:
b_list.append(a)
print(b_list)
# ['book', 'book', 'book']
Edit: You mentioned list comprehension. You are on the right track! You can do it with list comprehension like this:
a_list = ['book','book','cards','book','foo','foo','computer']
c_list = [a for a in a_list if a_list.count(a) > 2]
Good luck!
a = ['book','book','cards','book','foo','foo','computer']
list(filter(lambda s: a.count(s) > 2, a))
Your first attempt builds a dictionary with all of the counts. You need to take this a step further to get the items that you want:
res = [k for k in test if test[k] > 2]
Now that you have built this by hand, you should check out the builtin Counter class that does all of the work for you.
If you just want to print there are better answers already, if you want to remove you can try this.
a = ['book','book','cards','book','foo','foo','computer']
countdict = {}
for word in a:
if word not in countdict:
countdict[word] = 1
else:
countdict[word] += 1
for x, y in countdict.items():
if (2 >= y):
for i in range(y):
a.remove(x)
You can try this.
def my_filter(my_list, my_freq):
'''Filter a list of strings by frequency'''
# use set() to unique my_list, then turn set back to list
unique_list = list(set(my_list))
# count frequency in unique_list
frequencies = []
for value in unique_list:
frequencies.append(my_list.count(value))
# filter frequency
return_list = []
for i, frequency in enumerate(frequencies):
if frequency > my_freq:
for _ in range(frequency):
return_list.append(unique_list[i])
return return_list
a = ['book','book','cards','book','foo','foo','computer']
my_filter(a, 2)
['book', 'book', 'book']
I am making an program that simulates the roll of a dice 100 times. Now I want to sort the output of the random numbers that are given by the program. How do I have to do that?
import random
def roll() :
print('The computer will now simulate the roll of a dice 100 times')
list1 = print([random.randint(1,6) for _ in range(100)])
roll()
You do not have a list. The print() function returns None, not whatever it just printed to your terminal or IDE.
Store the random values, then print:
list1 = [random.randint(1,6) for _ in range(100)]
print(list1)
Now you can just sort the list:
list1 = [random.randint(1,6) for _ in range(100)]
list1.sort()
print(list1)
The above problem can also be solved using for loop as follows -
>>> import random
>>> mylist = []
>>> for i in range(100):
mylist.append(random.randint(1,6))
>>> print(mylist)
To sort the list, issue the following commands -
>>> sortedlist = []
>>> sortedlist = sorted(mylist)
>>> print(sortedlist)
If you don't need the original list:
list1.sort()
If you need the original list:
list2 = sorted(list1)
See python.org:
http://wiki.python.org/moin/HowTo/Sorting/