I have a list of lists with a certain range:
l = [["this", "is", "a"], ["list", "of"], ["lists", "that", "i", "want"], ["to", "copy"]]
And a list of words:
words = ["lorem", "ipsum", "dolor", "sit", "amet", "id", "sint", "risus", "per", "ut", "enim", "velit", "nunc", "ultricies"]
I need to create an exact replica of the list of lists, but with random terms picked from the other list.
This was the first thing that came to mind, but no dice.
for random.choice in words:
for x in list:
for y in x:
y = random.choice
Any ideas? Thank you in advance!
You can use list comprehensions for this:
import random
my_list = [[1, 2, 3], [5, 6]]
words = ['hello', 'Python']
new_list = [[random.choice(words) for y in x] for x in my_list]
print(new_list)
Output:
[['Python', 'Python', 'hello'], ['Python', 'hello']]
This is equivalent to:
new_list = []
for x in my_list:
subl = []
for y in x:
subl.append(random.choice(words))
new_list.append(subl)
With your example data:
my_list = [['this', 'is', 'a'], ['list', 'of'],
['lists', 'that', 'i', 'want'], ['to', 'copy']]
words = ['lorem', 'ipsum', 'dolor', 'sit', 'amet', 'id', 'sint', 'risus',
'per', 'ut', 'enim', 'velit', 'nunc', 'ultricies']
new_list = [[random.choice(words) for y in x] for x in my_list]
print(new_list)
Output:
[['enim', 'risus', 'sint'], ['dolor', 'lorem'], ['sint', 'nunc', 'ut', 'lorem'], ['ipsum', 'amet']]
You're not storing the values back into your lists. Try:
for i in range(0, len(list)):
subl = list[i]
for n in range(0, len(subl)):
list[i][n] = random.choice(words)
You should flatten your list of lists, then shuffle, then rebuild. Example:
import random
def super_shuffle(lol):
sublist_lengths = [len(sublist) for sublist in lol]
flat = [item for sublist in lol for item in sublist]
random.shuffle(flat)
pos = 0
shuffled_lol = []
for length in sublist_lengths:
shuffled_lol.append(flat[pos:pos+length])
pos += length
return shuffled_lol
print super_shuffle([[1,2,3,4],[5,6,7],[8,9]])
Prints:
[[7, 8, 5, 6], [9, 1, 3], [2, 4]]
This randomizes across ALL the lists, not just within a single sublist and guarantees no dups.
Related
I am trying to remove any strings from this list of strings if their length is greater than 5. I don't know why it is only removing what seems to be random strings. Please help. The item for sublist part of the code just changes the list of lists, into a normal list of strings.
list2 = [['name'],['number'],['continue'],['stop'],['signify'],['tester'],['racer'],['stopping']]
li = [item for sublist in list2 for item in sublist]
var=0
for words in li:
if len(li[var])>5:
li.pop()
var+=1
print(li)
The output is: ['name', 'number', 'continue', 'stop', 'signify']
Just include the check when flattening the list:
list2 = [['name'],['number'],['continue'],['stop'],['signify'],['tester'],['racer'],['stopping']]
li = [item for sublist in list2 for item in sublist if len(item) <= 5]
['name', 'stop', 'racer']
You can use a list comprehension to build a new list with only items that are 5 or less in length.
>>> l = ['123456', '123', '12345', '1', '1234567', '12', '1234567']
>>> l = [x for x in l if len(x) <= 5]
>>> l
['123', '12345', '1', '12']
list(filter(lambda x: len(x[0]) <= 5, list2))
How can I turn this
list = [['I','am','a','hero'],['What','time','is','it']]
to this
list = [["I am a hero"],["What time is it"]]
This doesn't work:
list(chain.from_iterable(list.str.split(',')))
And neither does:
[a for a in list]
You could join the list items:
list1 = [['I', 'am', 'a', 'hero'], ['What', 'time', 'is', 'it']]
list2 = [[' '.join(item)] for item in list1]
print(list2)
Output:
[['I am a hero'], ['What time is it']]
Here is one way of doing it
lst = [['I','am','a','hero'],['What','time','is','it']]
new_list = [[' '.join(x)] for x in lst]
print(new_list)
List1 = ['RELEASE', 'KM123', 'MOTOR', 'XS4501', 'NAME']
List2 = ['KM', 'XS', 'M']
Now I am using code that only searches List2 in List1 in any position.
Result = [ s for s in List1 if any(xs in s for xs in List2]
Output :
[KM123', 'MOTOR', 'XS4501', 'NAME']
But I don't want 'NAME' to be in the list because it contains 'M' not in the starting. Any help...
Use str.startswith() which checks if a string starts with a particular sequence of characters:
[s for s in List1 if any(s.startswith(xs) for xs in List2)]
Looks like you can use str.startswith
Ex:
List1 = ['RELEASE', 'KM123', 'MOTOR', 'XS4501', 'NAME']
List2 = ('KM', 'XS', 'M') #convert to tuple
result = [ s for s in List1 if s.startswith(List2)]
print(result) #-->['KM123', 'MOTOR', 'XS4501']
I have 2 lists of strings. I would like to combine them together to create list in lists like this one below.
[['Hello','praet:sg:m1:perf'], ['world', 'subst:pl:acc:n']]
How to do it? Somehow create instance of list in list or there is some "python magic"?
Thank you
zip (Python Docs) is what you are looking for. You can stitch together two lists in a list comprehension:
l1 = ['Hello', 'world']
l2 = ['praet:sg:m1:perf','subst:pl:acc:n']
zipped = [list(items) for items in zip(l1,l2)]
print(zipped)
Result:
[['Hello', 'praet:sg:m1:perf'], ['world', 'subst:pl:acc:n']]
There are many ways to do that.
ex-1: by using '+'
list1=['Hello', 'world']
list2 = ['praet:sg:m1:perf','subst:pl:acc:n']
print([list1]+[list2])
ex-2: by using append()
res =[]
list1=['Hello', 'world']
list2 = ['praet:sg:m1:perf','subst:pl:acc:n']
res.append(list1)
res.append(list2)
print(res)
ex-3: by using zip()
list1=['Hello', 'world']
list2 = ['praet:sg:m1:perf','subst:pl:acc:n']
res = [[l1, l2] for l1,l2 in zip(list1, list2)]
print(res)
I hope this helps:
list1=['Hello', 'world']
list2 = ['praet:sg:m1:perf','subst:pl:acc:n']
newlist = []
for i in range(len(list1)):
newlist.append([list1[i],list2[i]])
Just add the two list you have to another list:
list1 = ['Hello', 'praet:sg:m1:perf']
list2 = ['world', 'subst:pl:acc:n']
result = [list1, list2]
Another way:
result = []
list1 = ['Hello', 'praet:sg:m1:perf']
list2 = ['world', 'subst:pl:acc:n']
...
result.append(list1)
result.append(list2)
Use zip
list1=['Hello', 'world']
list2 = ['praet:sg:m1:perf','subst:pl:acc:n']
result = [[x, y] for x,y in zip(list1, list2)]
print(result)
Output:
[['Hello', 'praet:sg:m1:perf'], ['world', 'subst:pl:acc:n']]
I am trying to add "!" after every variable in a list.
But my code only adds the series of "!" after the initial list.
For example:
lst = [1,2,3,4]
def addmark(lst):
emptylst = []
for n in range(0, len(lst)):
lst.append("!")
return lst
This would return [1,2,3,4,"!", "!", "!", "!"]
I want to reuturn [1, "!", 2, "!", 3, "!", 4, "!"]
def addmark(lst):
emptylst = []
for i in lst:
emptylst.append(i)
emptylst.append("!")
return emptylst
An alternative to the accepted answer using itertools:
from itertools import chain, repeat
lst = [1, 2, 3]
marker = repeat("!")
list(chain.from_iterable(zip(lst, marker)))
>>> [1, '!', 2, '!', 3, '!']
Using insert:
list.insert (i, x)
Insert an item at a given position. The first
argument is the index of the element before which to insert, so
a.insert(0, x) inserts at the front of the list, and a.insert(len(a),
x) is equivalent to a.append(x).
Reference: docs.python.org/2/tutorial/datastructures
Code:
def addmark(lst):
add = 0 # needed cause after every insertion of '!' the position where you want to add the next '!' changes
for i in range (1,len(lst)+1): # (start: adding after ls[0], finish: adding after the last element)
lst.insert(i+add, '!')
add += 1
return lst
this is code
#!/usr/bin/env python
# coding:utf-8
'''黄哥Python'''
def addmark(lst):
result = []
for i, item in enumerate(lst):
result.append(item)
result.append("!")
return result
if __name__ == '__main__':
lst = [1,2,3,4]
print addmark(lst)
create a list of lists then flatten
lst = [1,2,3,4]
lst2 = [[i,'!'] for i in lst]
lst3 = [item for sublist in lst2 for item in sublist]
print lst2
print lst3
>>> [[1, '!'], [2, '!'], [3, '!'], [4, '!']]
>>> [1, '!', 2, '!', 3, '!', 4, '!']
as a one liner:
lst = [1,2,3,4]
lst2 = [item for sublist in [[i,'!'] for i in lst] for item in sublist]
print lst2
>>> [1, '!', 2, '!', 3, '!', 4, '!']