Let's say we've got a few lists as follows:
list1 = ['hi', 'hello', 'goodbye', 'caio', 1.0]
list2 = ['hi', 'bye', 1.0]
list3 = ['hi', 'bye', 'hello', 2.0]
I want to get it in this format:
newList1 = [['hi', 'hello'], ['hello', 'goodbye'], ['goodbye', 'caio'], ['caio', 1.0]]
newList2 = [['hi', 'bye'], ['bye', 1.0]]
newList3 = [['hi', 'bye'], ['bye', 'hello'], ['hello', 2.0]]
My current method is looping through the list based on len(), and appending [listN[i], listN[i+1], but this is running within another for loop of a huge dataset, so O(n^2) is brutal. Is there any way to increase the performance?
Thanks.
You can do like this,
list1 = ['hi', 'hello', 'goodbye', 'caio', 1.0]
newList1 = list(zip(list1, list1[1:]))
# Result
[('hi', 'hello'), ('hello', 'goodbye'), ('goodbye', 'caio'), ('caio', 1.0)]
Edit
If you want a list of list,
list(map(list, zip(list1, list1[1:])))
# Result
[['hi', 'hello'], ['hello', 'goodbye'], ['goodbye', 'caio'], ['caio', 1.0]]
I like the solution proposed by #Rahul K P, but here is another option. List comprehension is always almost faster than a loop, so you can do it like this:
list1 = ['hi', 'hello', 'goodbye', 'caio', 1.0]
newList1 = [list1[i:i+2] for i in range(len(list1)-1)]
I would appreciate if you test all 3 solutions and share the results.
Related
This question already has answers here:
Python - get the last element of each list in a list of lists
(5 answers)
Closed 2 years ago.
I have some nested lists. I want to extract the last occurring element within each sublist (eg 'bye' for the first sublist). I then want to add all these last occurring elements ('bye', 'bye', 'hello' and 'ciao') to a new list so that I can count them easily, and find out which is the most frequently occurring one ('bye).
The problem is that my code leaves me with an empty list. I've looked at Extracting first and last element from sublists in nested list and How to extract the last item from a list in a list of lists? (Python) and they're not exactly what I'm looking for.
Thanks for any help!
my_list = [['hello', 'bye', 'bye'], ['hello', 'bye', 'bye'], ['hello', 'hello', 'hello'], ['hello', 'bye', 'ciao']]
# Make a new list of all of the last elements in the sublists
new_list = []
for sublist in my_list:
for element in sublist:
if sublist.index(element) == -1:
new_list.append(element)
# MY OUTPUT
print(new_list)
[]
# EXPECTED OUTPUT
['bye', 'bye', 'hello', 'ciao']
# I would then use new_list to find out what the most common last element is:
most_common = max(set(new_list), key = new_list.count)
# Expected final output
print(most_common)
# 'bye'
You can call the last element of a list by calling the index -1, e.g. sublist[-1]. The following code should give you your expected result:
my_list = [['hello', 'bye', 'bye'], ['hello', 'bye', 'bye'], ['hello', 'hello', 'hello'], ['hello', 'bye', 'ciao']]
new_list = list()
for sublist in my_list:
new_list.append(sublist[-1])
print(new_list)
or as Risoko pointed out, you can do it in one line, so the code should look like
my_list = [['hello', 'bye', 'bye'], ['hello', 'bye', 'bye'], ['hello', 'hello', 'hello'], ['hello', 'bye', 'ciao']]
new_list = [sublist[-1] for sublist in my_list]
print(new_list)
You are looking for this:
for sublist in my_list:
new_list.append(sublist[-1])
The index -1 does not "really exist", it is a way to tell python to start counting from the end of the list. That is why you will not get a match when looking for -1 like you do it.
Additionally, you are walking over all the lists, which is not necessary, as you have "random access" by fetching the last item as you can see in my code.
There is even a more pythonic way to do this using list comprehensions:
new_list = [sublist[-1] for sublist in my_list]
Then you do not need any of those for loops.
output = [sublist[-1] for sublist in my_list]
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 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.
This question already has answers here:
How to remove an element from a list by index
(18 answers)
Closed 7 years ago.
Is there an easy way to delete an entry in a list? I would like to only remove the first entry. In every forum that I have looked at, the only way that I can delete one entry is with the list.remove() function. This would be perfect, but I can only delete the entry if I know it's name.
list = ['hey', 'hi', 'hello', 'phil', 'zed', 'alpha']
list.remove(0)
This doesn't work because you can only remove an entry based on it's name. I would have to run list.remove('hey'). I can't do this in this particular instance.
If you require any additional information, ask.
These are methods you can try:
>>> my_list = ['hey', 'hi', 'hello', 'phil', 'zed', 'alpha']
>>> del my_list[0]
>>> my_list = ['hey', 'hi', 'hello', 'phil', 'zed', 'alpha']
>>> if 'hey' in my_list: # you're looking for this one I think
... del my_list[my_list.index('hey')]
...
>>> my_list
['hi', 'hello', 'phil', 'zed', 'alpha']
You can also use filter:
my_list = filter(lambda x: x!='hey', my_list)
Using list comprehension:
my_list = [ x for x in my_list if x!='hey']
First of all, never call something "list" since it clobbers the built-in type 'list'. Second of all, here is your answer:
>>> my_list = ['hey', 'hi', 'hello', 'phil', 'zed', 'alpha']
>>> del my_list[1]
>>> my_list
['hey', 'hello', 'phil', 'zed', 'alpha']
Lists work with positions, not keys (or names, whatever you want to call them).
If you need named access to your data structure consider using a dictionary instead which allows access to its value by using keys which map to the values.
d = {'hey':0, 'hi':0, 'hello':0, 'phil':0, 'zed':0, 'alpha':0}
del d['hey']
print(d) # d = {'alpha': 0, 'hello': 0, 'hi': 0, 'phil': 0, 'zed': 0}
Otherwise you will need to resort to index based deletion by getting the index of the element and calling del alist[index].
To add to the poll of answers..how about:
>>> my_list = ['hey', 'hi', 'hello', 'phil', 'zed', 'alpha']
>>> my_list=my_list[1:]
>>> my_list
['hi', 'hello', 'phil', 'zed', 'alpha']
l = [
{'bob':'hello','jim':'thanks'},
{'bob':'world','jim':'for'},
{'bob':'hey','jim':'the'},
{'bob':'mundo','jim':'help'}
]
for dict in l:
print dict['jim']
Is there a one liner or pythonic way of doing this?
I'm trying to retrieve a list of just 1 item in a list of dictionaries
[d['jim'] for d in l]
And don't use dict as a variable name. It masks the dict() built-in.
Yes, with good ol' functional programming:
map(lambda d: d['jim'], l)
Sure, for example:
In []: l
Out[]:
[{'bob': 'hello', 'jim': 'thanks'},
{'bob': 'world', 'jim': 'for'},
{'bob': 'hey', 'jim': 'the'},
{'bob': 'mundo', 'jim': 'help'},
{'bob': 'gratzie', 'jimmy': 'a lot'}]
In []: [d['jim'] for d in l if 'jim' in d]
Out[]: ['thanks', 'for', 'the', 'help']