I am trying to convert this tuple into a list, however when I run this code:
mytuple=('7578',), ('6052',), ('8976',), ('9946',)
List=[]
for i in mytuple:
Start,Mid,End = map(str, mytuple.split("'"))
List.append(Mid)
print(List)
I receive this error:
AttributeError: 'tuple' object has no attribute 'split'
The output should be:
[7578, 6052, 8976, 9946]
this is what you are looking for
mytuple = (('7578',), ('6052',), ('8976',), ('9946',))
result = [int(x) for x, in mytuple]
print(result)
If I understood correctly, this is want you want:
mytuple = ('7578',), ('6052',), ('8976',), ('9946',)
result = [e for e, in mytuple]
print(result)
Output
['7578', '6052', '8976', '9946']
I would use itertools.chain.from_iterable (which errs on the side of too much verbosity than too little):
from itertools import chain
result = [int(x) for x in chain.from_iterable(mytuple)]
# vs ... for x, in mytuple]; the comma is easy to miss
Somewhere between the two extremes would be
result = [int(x) for x in chain(*mytuple)]
Related
I have a list of strings consisting of integers, and I am trying to replace them with the sum of their digits. E.g. nums = ["12","23","33"] -> nums = [3,5,6]
Here is my code:
strng = ['12','23','33']
for i in range(len(strng)):
print(list((map(lambda x:int[x],list(strng[i])))))
For the above I am getting a TypeError: 'type' object is not subscriptable. It works up until map(), but when I add the list(map(...)), I get this error.
Any ideas how to fix it?
My after this is fixed, my idea is to do the following:
strng = ['12','23','33']
for i in range(len(strng)):
strng[i] = sum(list((map(lambda x:int[x],list(strng[i]))))))
Which should replace each of strng with the sum of its digits.
The error you're getting is you because you wrote int[x] instead of int(x). However, there are some additional issues with your existing solution.
The short and pythonic solution to this problem would be:
answer = [sum(map(int, list(s))) for s in strng]
To break this down:
[... for s in strng]: this is a list comprehension
list(s): This takes each string and converts it into a list of str of each character, so "123" becomes ["1","2","3"]
map(int, list(s)): This applys the int conversion to each element in list(s), so ["1","2","3"] becomes [1,2,3]
sum(...): We take the sum of the resulting list of ints
The equivalent of the above using a normal for loop would be something like this:
answer = []
for s in strng:
list_of_chars = list(s)
list_of_ints = map(int, list_of_chars)
sum_of_ints = sum(list_of_ints)
answer.append(sum_of_ints)
You can use comprehension, and iterate each digits, convert them to integer, finally pass it to sum builtin to get sum of the values.
>>> [sum(int(i) for i in v) for v in strng]
[3, 5, 6]
Not really efficient, but try this :
strng = ['12','23','33']
def function(strng) :
my_list = []
for string in strng :
my_list.append(0)
for digit in string :
my_list[-1] += int(digit)
return my_list
strng = function(strng)
print(strng)
I tried to sort list within a list but failed to do so , Is something wrong with my code ?
x = [[int(i)] for i in raw_input().split()]
print x
q = x.sort(key=lambda p: p[0])
print q
Before this I tried simpler code such as:
x = [[int(i)] for i in raw_input().split()]
print (x.sort())
But the result is same in both cases :
list.sort is an in-place operation that returns None. So you're assigning None.
If you want a new list to be returned as a value use sorted:
q = sorted(x, key=...)
print(q)
If you want to mutate the x in place use:
x.sort(...)
print(x)
Tip - to get a flat list use:
from itertools import chain
q = list(chain.from_iterable(x))
And now if you want to sort:
q = sorted(q) # no need for key
I've checked every other post about this, but none can fix my issue.
I made a list that holds tuples with an id and a datetime object. Everytime I try to clean up the list with:
last_encounters = [item for item in last_encounters if item[1] < datetime.utcnow]
I get the error that 'datetime.datetime' object is not subscriptable. It's getting pretty annoying, I tried dicts.. didn't work.
Also tested the item[1], according to my print it is a datetime.
Even tried changing it to (x,y) for x,y in last_encounters if y < ... also did NOT work.
Some useful code:
list = []
d_t = datetime.utcfromtimestamp(9000000)
list += [('lel', d_t)]
list = [item for item in list if item[1] < datetime.utcnow]
I hope someone can tell me what I am doing wrong here.
Thanks in advance,
Kevin
When you do last_encounters += (a, b), you are adding two sequences together, last_encounters and (a,b). This means you end up with a and b stuck on the end of the list, rather than just adding the tuple to the list.
There are two options to fix your problem:
Add a sequence containing your tuple:
last_encounters += [(d["id"], d["d_t"])]
Or preferably, use the append method:
last_encounters.append((d["id"], d["d_t"]))
It looks like your problem is the way you add the tuple to the list. Here is an example to show the problem :
l = []
l += ("a", "b")
print l
l = []
l.append( ("a", "b"))
print l
Which gives :
>>> ['a', 'b']
>>> [('a', 'b')]
So list+=tuple is equivalent to calling list.extend(tuple) and not list.append(tuple) which is what you want.
A side note on the meaning of the exception that was raised :
X is not subscriptable means that your are trying to call that syntax X[some int] while the object doesn't support it.
Try calling utcnow as a method utcnow():
last_encounters = [item for item in last_encounters if item[1] < datetime.utcnow()]
I couldn't reproduce your error with a version of your code, but a version with items in the list lead to this fix.
I created a list of lists and then tried to get a distinct list of the lists using set(), but it appears as though i cant use list on a set.
Is there another way to accomplish this with a concise statement that performs well?
CODE
x = [1,2]
y = [1,2]
z = [2,3]
xyz = []
xyz.append(x)
xyz.append(y)
xyz.append(z)
set(xyz)
Error
TypeError: unhashable type: 'list'
Goal
xyz = [[1,2],[2,3]]
if you want to preserve order and keep your lists, you could use generator function to remove the dupes from your list:
xyz = [x, y, z]
def remove_dupe_subs(l):
seen = set()
for sub in l:
tup = tuple(sub)
if tup not in seen:
yield sub
seen.add(tup)
xyz[:] = remove_dupe_subs(xyz)
Or using a generator expression taking advantage of the fact set.add returns None :
seen = set()
xyz[:] = (seen.add(tup) or sub for sub, tup in zip(xyz, map(tuple, xyz)) if tup not in seen)
print(xyz)
If the list members are hashable, it will work
x = [1,2]
y = [1,2]
z = [2,3]
xyz = []
xyz.append(tuple(x))
xyz.append(tuple(y))
xyz.append(tuple(z))
print xyz
xyz_set = set(xyz)
print xyz_set
It's a little bit convoluted, but this will do the trick in a single line:
xyz=[list(x) for x in list(set((tuple(x),tuple(y),tuple(z))))]
The return value of sort() is None so the following code doesn't work:
def sorted_unique_items(a):
return list(set(a)).sort()
Any idea for better solution?
Use sorted():
sorted(set(a))
and you can omit the list() call entirely.
Its simple Just use the sorted() method :
data = [10,5,46,4]
sorted_data = sorted(data)
print "Sorted Data ::::",sorted_data
Above solution is only work for hashable type like string,integer and tuple but it not work for unhashable type like list.
for example if you have a list data= [[2],[1],[2],[4]]
for unhashable type best solution is :
from itertools import izip, islice
values= [[2],[1],[2],[4]]
def sort_unique_unhashable(values):
values = sorted(values)
if not values:
return []
consecutive_pairs = izip(values, islice(values, 1, len(values)))
result = [a for (a, b) in consecutive_pairs if a != b]
result.append(values[-1])
return result
print sort_unique_unhashable(values)
There is Two options:
a = [2,34,55,1,22,11,22,55,1]
#First option using sorted and set.
sorted(set(a))
#second option using list and set.
list(set(a))