Adding list python - python

Help! What do I have to change so that it comes out like this?
[('Mavis', 3), ('Ethel', 1), ('Rick', 2), ('Joseph', 5), ('Louis', 4)]
Right now, with my code, it comes out like this.
bots_status = [(bot_one_info) + (bot_two_info) + (bot_three_info) + (bot_four_info) + (bot_five_info)]
[('Mavis', 3, 'Ethel', 1, 'Rick', 2, 'Joseph', 5, 'Louis', 4)]

Place commas instead of + signs between your bots.
If working with a variable amount of entries, initialize an array and add to it using append.
bots_status = []
for bot_info in bot_infos:
bots_status.append(bot_info)

Replace the plusses (+) by commas (,) to make this a list of tuples instead of a list of one concatenated tuple:
bots_status = [bot_one_info, bot_two_info, bot_three_info, bot_four_info, bot_five_info]
Since your bot_x_info variables already are tuples, you also don’t need to use parentheses around the names (those don’t do anything).
The problem with your code was that you were using + on the tuples. The add operator concatenates tuples to a single one:
>>> (1, 2) + (3, 4)
(1, 2, 3, 4)
That’s why you ended up with one giant tuple in your list.
What you wanted is have each tuple as a separate item in the list, so you just need to create a list from those. Just like you would do [1, 2, 3] to create a list with three items, using a comma to separate each item, you also do this with other values, e.g. tuples in your case.

Let's say:
bot_one_info = ('Mavis', 3)
bot_two_info = ('Mavi', 3)
If you use +
lis = [bot_one_info + bot_two_info]
print lis
#Output
[('Mavis', 3, 'Mavi', 3)]
But if you use ,
lis = [bot_one_info,bot_two_info]
print lis
#Output
[('Mavis', 3), ('Mavi', 3)]
You can use here , instead of +.

Related

Explain the parenthesis syntax used in map

I am trying to remove the floating point in the tuple using a lambda function.
I am slicing the tuple and converting the last element in the tuple to int and concatenating it.
xyz = list((filter(lambda x : x[2].is_integer(), sides_triplet )))
print(xyz)
xy = list(map(lambda tup : tup[:2] + (int(tup[2]),), xyz))
print(xy)
Output:
[(3, 4, 5.0), (6, 8, 10.0)]
[(3, 4, 5), (6, 8, 10)]
The code works perfectly fine but my question is on the line:
xy = list(map(lambda tup : tup[:2] + (int(tup[2]),), xyz))
Need explanation as to why we use comma and then close the braces after int.
Instead if I use the line below, it throws an error, why is that?
xy = list(map(lambda tup : tup[:2] + (int(tup[2])), xyz))
Output:
xy = list(map(lambda tup : tup[:2] + (int(tup[2])), xyz))
TypeError: can only concatenate tuple (not "int") to tuple
see below
data = [(3, 4, 5.0), (6, 8, 10.0)]
new_data = [(x[0], x[1], int(x[2])) for x in data]
print(new_data)
output
[(3, 4, 5), (6, 8, 10)]
The main thing to understand and in answer toyour question about why the comma is needed before the closing bracket and why it fails when you dont include the comma.
When you want to create a tuple in python which has a single value you need to end it with a comma to tell python this is a tuple with a single value. Other wise python considers it just as an expression and will evaluate it and return the value of that expression (in this case an int)
first = (int("1"))
second = (int("1"),)
print(f"type={type(first)}, value={first}")
print(f"type={type(second)}, value={second}")
OUTPUT
type=<class 'int'>, value=1
type=<class 'tuple'>, value=(1,)
It doesnt work in your example without the comma becuase you are trying to concat the first value (a tuple) to the second value an int, and python wont allow that. By adding in the comma you create a tuple with a single value which is an int. These can then be concat together as both are tuples.

How to circumvent slow search with Index() method for a large list

I have a large list myList containing tuples.
I need to remove the duplicates in this list (that is the tuples with same elements in the same order). I also need to keep track of this list's indices in a separate list, indexList. If I remove a duplicate, I need to change its index in indexList to first identical value's index.
To demonstrate what I mean, if myList looks like this:
myList = [(6, 2), (4, 3), (6, 2), (8, 1), (5, 4), (4, 3), (2, 1)]
Then I need to construct indexList like this:
indexList = (0, 1, 0, 2, 3, 1, 4)
Here the third value is identical to first, so it (third value) gets index 0. Also the subsequent value gets an updated index of 2 and so on.
Here is how I achieved this:
unique = set()
i = 0
for v in myList[:]:
if v not in unique:
unique.add(v)
indexList.append(i)
i = i+1
else:
myList.pop(i)
indexList.append(myList.index(v))
This does what I need. However index() method makes the script very slow when myList contains hundreds of thousands of elements. As I understand this is because it's an O(n) operation.
So what changes could I make to achieve the same result but make it faster?
If you make a dict to store the first index of each value, you can do the lookup in O(1) instead of O(n). So in this case, before the for loop, do indexes = {}, and then in the if block, do indexes[v] = i and in the else block use indexes[v] instead of myList.index(v).

How to change a list to be used as a dictionary key

I have a list of lists with 4 elements in each of them.
LoL=[[1,1,1,1],[4,2,3,[1,3]],[4,5,3,[0,4]]]
The 4th elements can be a list of two parts like [0,4] in [4,5,3,[0,4]].
I need to use its elements as keys for a dictionary,
Pseudo code:
dic = { [1,1,1,1]:'a',[4,2,3,[1,3]]:'b',[4,5,3,[0,4]]:'c' }
so tried to change them to tuples.
It works for simple lists (like [1,1,1,1]), but for the ones containing another list (like [4,5,3,[0,4]]) it raises an error:
dic[tuple([1,1,1,1])]=['bla','blah']
print dic
{(1, 1, 1, 1): ['bla', 'blah']}
dic[tuple([4, 2, 3, [1, 3]])]=['blablah']
TypeError: unhashable type: 'list'
I need to reuse the keys as lists later. So trying to change elements of LoL to strings (e.g. using repr()) is not an option!
Edit:
I know why lists cannot be used as dictionary keys. Here they are not changed while in the dic. I just need some way to pass them to another module to extract them.
Just convert your nested lists to nested tuples. Here's a quick demo. It's not perfect, but it works.
#! /usr/bin/env python
LoL = [[1,1,1,1],[4,2,3,[1,3]],[4,5,3,[0,4]]]
def nested_list_to_tuple(nlist):
return tuple([nested_list_to_tuple(i) if isinstance(i, list) else i for i in nlist])
ToT = nested_list_to_tuple(LoL)
print ToT
output
((1, 1, 1, 1), (4, 2, 3, (1, 3)), (4, 5, 3, (0, 4)))
Just use tuples:
a = {}
a[(4, 2, 3, (1, 3))] = ['blablah']
print(a)
Output:
{(4, 2, 3, (1, 3)): ['blablah']}

Removing specific tuples from List

I've got a list
a = [(1,2),(1,4),(2,6),(1,8),(3,6),(1,10),(1,6)]
If I say that:
for x in a:
if x[0]==1:
print x
I get the expected result : (1,2) (1,4) (1,8) (1,10) (1,6)
However I want to remove all the occurrences of all the tuples in the format (1,x),So
for x in a:
if x[0]==1:
a.remove(x)
I thought that all the occurences should be removed.However when i say
Print a
I get [(1,4),(2,6),(3,6),(1,6)]
Not all the tuples were removed. How do I do it.??
Thanks
I'd use list comprehension:
def removeTuplesWithOne(lst):
return [x for x in lst if x[0] != 1]
a = removeTuplesWithOne([(1,2),(1,4),(2,6),(1,8),(3,6),(1,10),(1,6)])
For me it's more pythonic than built-in filter function.
P.S. This function does not change your original list, it creates new one. If your original list is huge, i'd probably use generator expression like so:
def removeTuplesWithOne(lst):
return (x for x in lst if x[0] != 1)
This isn't the same approach as yours but should work
a = filter(lambda x: x[0] != 1, a)
You can use list comprehension like this, to filter out the items which have 1 as the first element.
>>> original = [(1, 2), (1, 4), (2, 6), (1, 8), (3, 6), (1, 10), (1, 6)]
>>> [item for item in original if item[0] != 1]
[(2, 6), (3, 6)]
This creates a new list, rather than modifying the existing one. 99% of the time, this will be fine, but if you need to modify the original list, you can do that by assigning back:
original[:] = [item for item in original if item[0] != 1]
Here we use slice assignment, which works by replacing every item from the start to the end of the original list (the [:]) with the items from the list comprehension. If you just used normal assignment, you would just change what the name original pointed to, not actually modify the list itself.
You can do it with a generator expression if you're dealing with huge amounts of data:
a = [(1,2),(1,4),(2,6),(1,8),(3,6),(1,10),(1,6)]
# create a generator
a = ((x,y) for x, y in a if x == 1)
# simply convert it to a list if you need to...
>>> print list(a)
[(1, 2), (1, 4), (1, 8), (1, 10), (1, 6)]

python - how do you store elements in a tuple

how to store elements in a tuple?
I did this:
for i in range (0, capacity):
for elements in self.table[i]:
# STORE THE ALL THE ELEMENTS IN THE TUPLE
tuples are immutable. You can create a tuple. But you cannot store elements to an already created tuple. To create (or convert) your list of elements to a tuple. Just tuple() it.
t = tuple([1,2,3])
In your case it is
t = tuple(self.table[:capacity])
Since you haven't told us - we can only guess what table looks like
If it is a list of lists for example, you can do this to get a tuple of tuples
>>> table =[[1,2,3],[4,5,6],[7,8,9]]
>>> tuple(map(tuple, table))
((1, 2, 3), (4, 5, 6), (7, 8, 9))
>>> capacity=2
>>> tuple(map(tuple, table[:capacity]))
((1, 2, 3), (4, 5, 6))
It's as easy as t = tuple(self.table[i])
I think this is what you want.
x = []
for i in range (0, capacity):
for elements in self.table[i]:
x.append(elements)
t = tuple(x)

Categories

Resources