Is there a way to get one value from a tuple in Python using expressions?
def tup():
return (3, "hello")
i = 5 + tup() # I want to add just the three
I know I can do this:
(j, _) = tup()
i = 5 + j
But that would add a few dozen lines to my function, doubling its length.
You can write
i = 5 + tup()[0]
Tuples can be indexed just like lists.
The main difference between tuples and lists is that tuples are immutable - you can't set the elements of a tuple to different values, or add or remove elements like you can from a list. But other than that, in most situations, they work pretty much the same.
For anyone in the future looking for an answer, I would like to give a much clearer answer to the question.
# for making a tuple
my_tuple = (89, 32)
my_tuple_with_more_values = (1, 2, 3, 4, 5, 6)
# to concatenate tuples
another_tuple = my_tuple + my_tuple_with_more_values
print(another_tuple)
# (89, 32, 1, 2, 3, 4, 5, 6)
# getting a value from a tuple is similar to a list
first_val = my_tuple[0]
second_val = my_tuple[1]
# if you have a function called my_tuple_fun that returns a tuple,
# you might want to do this
my_tuple_fun()[0]
my_tuple_fun()[1]
# or this
v1, v2 = my_tuple_fun()
Hope this clears things up further for those that need it.
General
Single elements of a tuple a can be accessed -in an indexed array-like fashion-
via a[0], a[1], ... depending on the number of elements in the tuple.
Example
If your tuple is a=(3,"a")
a[0] yields 3,
a[1] yields "a"
Concrete answer to question
def tup():
return (3, "hello")
tup() returns a 2-tuple.
In order to "solve"
i = 5 + tup() # I want to add just the three
you select the 3 by:
tup()[0] # first element
so all together:
i = 5 + tup()[0]
Alternatives
Go with namedtuple that allows you to access tuple elements by name (and by index). Details are at https://docs.python.org/3/library/collections.html#collections.namedtuple
>>> import collections
>>> MyTuple=collections.namedtuple("MyTuple", "mynumber, mystring")
>>> m = MyTuple(3, "hello")
>>> m[0]
3
>>> m.mynumber
3
>>> m[1]
'hello'
>>> m.mystring
'hello'
Related
I've had a look through the forums and can't find anything to do with multiplying all elements in an array recursively.
I've created the following code that almost does what I want. The goal is to use no loops and only recursion.
Here's the code:
def multAll(k,A):
multAllAux(k,A)
return A[:]
def multAllAux(k,A):
B = [0]
if A == []:
return 0
else:
B[0] = (A[0] * k)
B.append(multAllAux(k,A[1:]))
return B
print(multAllAux(10, [5,12,31,7,25] ))
The current output is:
[50, [120, [310, [70, [250, 0]]]]]
However, it should be:
[50,120,310,70,250]
I know I am close, but I am at a complete loss at this point. The restrictions of no loops and solely recursion has left me boggled!
Your multAllAux function returns a list. If you append a list to another list, you get this nested list kind of structure that you are getting right now.
If you instead use the "extend" function; it will work as expected.
>>> a = [1, 2, 3]
>>> a.extend([4, 5])
>>> a
[1, 2, 3, 4, 5]
extend takes the elements from a second list and adds them to the first list, instead of adding the second list itself which is what append does!
Your function also returns a zero at the end of the list, which you don't need. You can try this:
def mult(k, A: list) -> list:
return [k * A[0]] + mult(k, A[1:]) if A else []
The problem is here:
B.append(multAllAux(k,A[1:])))
What .append(..) does is it takes the argument, considers it as a single element and adds that element to the end of the list. What you want is to concatenate to the list (ie the item being added should be seen as a list of elements rather than one single element).
You can say something like: B = B + multAllAux(..) or just use +=
B += multAllAux(...)
BTW, if you wanted to multiply a single number to a list, there is a very similar construct: map(..). Note that this behaves slightly differently depending on whether you're using Py2 or Py3.
print(map(lambda x: x * 10, [5,12,31,7,25]))
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I would like to store more than 1 value in a python array(I am open to any other data structure too).
For example :
array[1][2][3] = 1 # (this is what I am able to do now)
But later I also get the value 2, now instead of storing it in another array using the same indices, I want to be able to do this :
array[1][2][3] = 1,2
But I dont want to concatenate the existing result like in a string, and split the string to get the individual values.
Is there a way of doing this without having to introduce another dimension to the array?
edit : I want a neater way to store 2 values in the same cell.
Thanks
I would use defaultdict for this:
from collections import defaultdict
array = defaultdict(list)
array[(1,2,3)].append(1)
array[(1,2,3)].append(2)
Now array at position (1,2,3) is a list containing 1 and 2
If understand correctly, you can store new list with values you need in array[1][2][3] instead of single value:
array[1][2][3] = [1] # instead of = 1
array[1][2][3].append(2) # now it's [1, 2]
array[1][2][3].extend([3,4]) # now it's [1, 2, 3, 4]
all_values = array[1][2][3] # no another dimensions uses to get values
If you know all the contents a priori you may use a tuple. Here I will create pairs of numbers (n, n+1) and store them in a list:
>>> l = [(n,n+1) for n in xrange(0,4)]
>>> l
[(0, 1), (1, 2), (2, 3), (3, 4)]
If you decide you want to append another value, you can. Assume you want to append 3 to the tuple (1,2):
>>> l[1] = l[1] + (3,)
>>> l
[(0, 1), (1, 2, 3), (2, 3), (3, 4)]
Tuples are immutable, so they're faster than lists for construction, but you can't make changes to an instantiated tuple - you must replace it. If you're fairly certain your data won't change, use a tuple. If it will (and often), use a list.
Edit
If you want the values from the tuple, you can do the following:
>>> tup = l[0]
>>> tup
(0, 1)
>>> x, y = tup
>>> x
0
>>> y
1
>>> t, u = l[2] # alternatively
>>> t
2
>>> u
3
array[1][2][3] = 1,2
Seems like you want to have a list in array[1][2][3], which you could actually do with
array[1][2][3] = [1,2]
or alternatively, as already mentionned by others with variations of
array[1][2][3] = []
array[1][2][3].append(1)
array[1][2][3].extend([2])
Mind the fact that use of t-uples is also possible
array[1][2][3] = (1,2)
But in this case, you won't be able to extend your "list" nor to modify its content (t-uples are indeed constant arrays, in size as well as in content.).
Is there a way of doing this without having to introduce another
dimension to the array?
Well... this requirement seems rather antagonistic with your previous one.
array[1][2][3] = 1,2
suggests that your are able to differentiate between "array[1][2][3][0]" (=1) and "array[1][2][3][1]" (=2). So, unless I don't understand your question, the short answer is "no" :)
I am simply trying to remove both entries if one is duplicate...for example if the array is
(9,1,2,2,3,4)...I need to output (9,1,3,4)
Most of the pandas methods like drop_duplicates() keep either the top or bottom entry. My data has always double duplicates and even number of elements always!
So example (1,4,6,7,3,3,0,0) output should be 1,4,6,7
import collections
a = (1,4,6,7,3,3,0,0)
a = [x for x,y in collections.Counter(a).items() if y == 1]
You have tuples there not arrays (lists in python use []). If you want to keep it as tuples you could do:
# if you need a new tuple
a = (1,4,6,7,3,3,0,0)
b = ()
for i in a:
if a.count(i) == 1:
b = b + (i,)
print b # (1, 4, 6, 7)
You could even do it in one line:
# if you want to replace the original tuple
a = tuple(i for i in a if a.count(i) == 1)
print a # (1, 4, 6, 7)
I have a tuple:
a = (1,2,3)
and I need to add a tuple at the end
b = (4,5)
The result should be:
(1,2,3,(4,5))
Even if I wrap b in extra parents:
a + (b), I get (1,2,3,4,5) which is not what I wanted.
When you do a + b you are simply concatenating both the tuples. Here, you want the entire tuple to be a part of another tuple. So, we wrap that inside another tuple.
a, b = (1, 2, 3), (4,5)
print a + (b,) # (1, 2, 3, (4, 5))
>>> a = (1,2,3)
>>> b = (4,5)
>>> a + (b,)
(1, 2, 3, (4, 5))
tuple objects are immutable. The result you're getting is a result of the fact that the + (and +=) operator is overridden to allow "extending" tuples the same way as lists. So when you add two tuples, Python assumes that you want to concatenate their contents.
To add an entire tuple onto the end of another tuple, wrap the tuple to be added inside another tuple.
c = a + (b,) # Add a 1-tuple containing the tuple to be added.
print(c) # >>> (1, 2, 3, (4, 5))
I'm new to Python and have a list of numbers. e.g.
5,10,32,35,64,76,23,53....
and I've grouped them into fours (5,10,32,35, 64,76,23,53 etc..) using the code from this post.
def group_iter(iterator, n=2, strict=False):
""" Transforms a sequence of values into a sequence of n-tuples.
e.g. [1, 2, 3, 4, ...] => [(1, 2), (3, 4), ...] (when n == 2)
If strict, then it will raise ValueError if there is a group of fewer
than n items at the end of the sequence. """
accumulator = []
for item in iterator:
accumulator.append(item)
if len(accumulator) == n: # tested as fast as separate counter
yield tuple(accumulator)
accumulator = [] # tested faster than accumulator[:] = []
# and tested as fast as re-using one list object
if strict and len(accumulator) != 0:
raise ValueError("Leftover values")
How can I access the individual arrays so that I can perform functions on them. For example, I'd like to get the average of the first values of every group (e.g. 5 and 64 in my example numbers).
Let's say you have the following tuple of tuples:
a=((5,10,32,35), (64,76,23,53))
To access the first element of each tuple, use a for-loop:
for i in a:
print i[0]
To calculate average for the first values:
elements=[i[0] for i in a]
avg=sum(elements)/float(len(elements))
Ok, this is yielding a tuple of four numbers each time it's iterated. So, convert the whole thing to a list:
L = list(group_iter(your_list, n=4))
Then you'll have a list of tuples:
>>> L
[(5, 10, 32, 35), (64, 76, 23, 53), ...]
You can get the first item in each tuple this way:
firsts = [tup[0] for tup in L]
(There are other ways, of course.)
You've created a tuple of tuples, or a list of tuples, or a list of lists, or a tuple of lists, or whatever...
You can access any element of any nested list directly:
toplist[x][y] # yields the yth element of the xth nested list
You can also access the nested structures by iterating over the top structure:
for list in lists:
print list[y]
Might be overkill for your application but you should check out my library, pandas. Stuff like this is pretty simple with the GroupBy functionality:
http://pandas.sourceforge.net/groupby.html
To do the 4-at-a-time thing you would need to compute a bucketing array:
import numpy as np
bucket_size = 4
n = len(your_list)
buckets = np.arange(n) // bucket_size
Then it's as simple as:
data.groupby(buckets).mean()