SO I am currently trying to do some exercises in python and i don't quite understand how to take a list of strings which is called s and build a new list of sub lists that is called as r.
So if i have an input
s = [ 'It is', 'time', 'for', 'tea' ]
the output list r should contain:
[ [0,'It is'], [1,'time'], [2,'for'], [3,'tea'] ]
Can someone please help me understand and get the answer?
I have tried to do this but its not the answer that i want.
def sub_lists(list1):
# store all the sublists
sublist = [[]]
# first loop
for i in range(len(list1) + 1):
# second loop
for j in range(i + 1, len(list1) + 1):
# slice the subarray
sub = list1[i:j]
sublist.append(sub)
return sublist
# driver code
s = [ 'It is', 'time', 'for', 'tea' ]
print(sub_lists(s))
You can use enumerate for this:
s = [ 'It is', 'time', 'for', 'tea' ]
r = [[index, value] for index, value in enumerate(s)]
print(r)
Output:
[[0, 'It is'], [1, 'time'], [2, 'for'], [3, 'tea']]
You can use enumerate():
s = [ 'It is', 'time', 'for', 'tea' ]
s = [[i,v] for i,v in enumerate(s)]
print(s)
Or, if you're not ready for that, you can use subscriptions:
s = [ 'It is', 'time', 'for', 'tea' ]
s = [[i,s[i]] for i in range(len(s))]
print(s)
Related
I'm trying to find the difference between two lists, but I would also like to know the position of the diff items.
My script isn't producing the results I want.
For example:
Here are the lists.
lst1 = ['dog', 'cat', 'plant', 'book', 'lamp']
lst2 = ['dog', 'mouse', 'plant', 'sock', 'lamp']
Here I am getting the position and value.
new_lst1 = [f"{i}, {v}" for i, v in enumerate(lst1)]
new_lst2 = [f"{i}, {v}" for i, v in enumerate(lst2)]
Then I want to find the difference between the two new lists.
def Diff(new_lst1, new_lst2):
(list(set(new_lst1) - set(new_lst2)))
Afterwards, I want to print the results.
print(new_lst1)
However, I'm getting:
['0, dog', '1, cat', '2, plant', '3, book', '4, lamp']
Sorry for the long explanation!
You split new_lst1, but left new_lst2 intact. First of all, this gets a run-time error, not the output you mention. If it did work, it gives you semantically incompatible elements to compare. Get rid of the split:
def Diff(new_lst1, new_lst2):
return list(set(new_lst1) - set(new_lst2))
# Afterwards, I want to print the results.
print(Diff(new_lst1, new_lst2))
Output:
['1, cat', '3, book']
You now have the correct information; format to taste.
It seems you're looking for the symmetric_difference of these lists:
>>> set(enumerate(lst1)) ^ set(enumerate(lst2))
{(1, 'mouse'), (1, 'cat'), (3, 'book'), (3, 'sock')}
Unless you're only looking for just the positions:
>>> [i for i, word in enumerate(lst1) if lst2[i] != word]
[1, 3]
You can refactor the following code into a function if you would like but this should accomplish what you're trying. Remember the first item in the list starts at 0 in python. So when it says difference at 1, it means the second item.
lst1 = ['dog', 'cat', 'plant', 'book', 'lamp']
lst2 = ['dog', 'mouse', 'plant', 'sock', 'lamp']
varying_pos = []
for index, item in enumerate(lst1):
if item != lst2[index]:
message = str(index) + ', ' + item
varying_pos.append(message)
print("The 2 lists vary at position:")
for value in varying_pos:
print(value)
I have two lists. The first one is a simple list with one entry:
l = [hello]
The second one is a nested list, with several thousand entries
i = [[world, hi],
[world, hi],
[world, hi],
[world, hi]]
Now I want to insert the entry from list l into the nested lists of i like this:
i = [[hello, world, hi],
[hello, world, hi],
[hello, world, hi],
[hello, world, hi]]
How can I do this?
You can use list comprehension to achieve that
i = [l+x for x in i]
Just use the insert method on each sublist in i.
for sublist in i:
sublist.insert(0, l[0])
If you don't want to modify i in place, and would prefer to build a new list, then
i = [[l[0], *sublist] for sublist in i]
simple: [[*l,*el] for el in i]
Output:
[['hello', 'world', 'hi'],
['hello', 'world', 'hi'],
['hello', 'world', 'hi'],
['hello', 'world', ' hi']]
I guess the benefits is that no matter how many elements you have in l, they will all be put in front of the stuff in i
Just add the element to the list you want
l = ["hello"]
i = [["world", "hi"],
["world", "hi"],
["world", "hi"],
["world", "hi"]]
x = []
for y in i:
x.append(l+y)
x
output:
[['hello', 'world', 'hi'],
['hello', 'world', 'hi'],
['hello', 'world', 'hi'],
['hello', 'world', 'hi']]
I believe something like this should do the trick:
l = ['hello']
i = [['world', 'hi'],
['world', 'hi'],
['world', 'hi'],
['world', 'hi']]
for j in i:
for k in l:
j = j.append(k)
I'm just iterating through your list i, nesting another for loop to iterate through the simpler list l (to account for the case whereby it has multiple elements), and simply appending each entry in l to the current list in i.
My question is semi-answered in
Python split for lists page. However, I need to split based on TWO consecutive components (not one component). And the code is in Python.
For example:
list = ["id","title","data","more data","id","title","data 2","more data 2","danger","id","title","date3","lll"]
and I want the following outcome:
new_list = [["id","title","data","more data"],["id","title","data 2","more data 2","danger"],["id","title","date3","lll"]]
Please help.
Danger: Don't use built-in function as variable names. list is built-in funtion in python.
Try this,
>>> list1 = ["id","title","data","more data","id","title","data 2","more data 2","danger","id","title","date3","lll"]
>>> new_list = []
>>> new_list_ = []
>>> for l in list1:
if list1[0]==l:
if new_list_:
new_list.append(new_list_)
new_list_ = []
new_list_.append(l)
if list1.index(l)==len(list1)-1:
new_list.append(new_list_)
Output:
>>> new_list
[['id', 'title', 'data', 'more data'], ['id', 'title', 'data 2', 'more data 2', 'danger'], ['id', 'title', 'date3', 'lll']]
>>>
you could do this in segments. First off, find all the indexes of 'id' where the following item is 'title'
lst = ["id","title","data","more data","id","title","data 2","more data 2","danger","id","title","date3","lll"]
lst_len = len(lst)
indexes = [i for i, v in enumerate(lst) if v=='id' and i+1 < lst_len and lst[i+1]=='title']
Then iterate over them as pairs and split appropriately.
import itertools
# from itertools recipes
def pairwise(iterable, fillvalue=None):
a, b = iter(iterable), iter(iterable)
next(b, None)
return itertools.zip_longest(a, b, fillvalue=fillvalue)
result = [lst[i:j] for i,j in pairwise(indexes)]
>>> result
[['id', 'title', 'data', 'more data'], ['id', 'title', 'data 2', 'more data 2', 'danger'], ['id', 'title', 'date3', 'lll']]
You could use that pairwise iterator to more quickly find the indexes, too.
indexes = [i for i, (a, b) in enumerate(pairwise(lst)) if a=='id' and b=='title']
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.
I'd like to replace the 'x-%' from the origin list with the values from 'anotherList' in loop.
As you can see, when looping through, only the last state is saved, because it replaces the standardList again.
What might be the best way to kind of 'save the state of every list' and then loop through it again?
Result should be:
result = ['I', 'just', 'try','to', 'acomplish', 'this','foo', 'list']
What I got so for:
originList = ['I', 'x-0', 'x-1','to', 'acomplish', 'x-2','foo', 'x-3']
anotherList = ['just','try','this','list']
for index in originList:
for num in range(0,4):
if 'x' in index:
result = str(originList).replace('x-%s'%(str(num)), anotherList[num])
print result
#['I', 'x-0', 'x-1', 'to', 'acomplish', 'x-2', 'foo', 'list'] <-- wrong :X
Thanks for any help because I can't figure it out at the moment
EDIT*
If there is a cleaner solution I would also appreciate to hear
This one avoids the creation of a new list
count = 0
for word in range(0, len(originList)):
if 'x-' in originList[word]:
originList[word] = anotherList[count]
count += 1
print originList
Here ya go!
>>> for original in originList:
if 'x' in original:
res.append(anotherList[int(original[-1])]) #grab the index
else:
res.append(original)
>>> res
['I', 'just', 'try', 'to', 'acomplish', 'this', 'foo', 'list']
>>>
Since the index of the value needed is in the items of originList, you can just use it, so no need for the extra loop. Hope this helps!
originList = ['I', 'x-0', 'x-1','to', 'acomplish', 'x-2','foo', 'x-3']
anotherList = ['just','try','this','list']
def change(L1, L2):
res = []
index = 0
for ele in L1:
if 'x-' in ele:
res.append(L2[index])
index += 1
else:
res += [ele]
return res
print(change(originList, anotherList))
The result:
['I', 'just', 'try', 'to', 'acomplish', 'this', 'foo', 'list']
originList = ['I', 'x-0', 'x-1','to', 'acomplish', 'x-2','foo', 'x-3']
anotherList = ['just','try','this','list']
res = []
i=0
for index in originList:
if 'x' in index:
res.append(anotherList[i])
i += 1
else:
res.append(index)
print res
you can get right result!
But,I think you have use string.format(like this)
print '{0}{1}{2}{3}'.format('a', 'b', 'c', 123) #abc123
Read python docs - string