Questions tagged [tuples]

1

votes
3

answer
27

Views

Comparison of list to list of lists and return the other element from the list of list

I have a list - answers: [0,1] and another list of list - questions: [[0,ABC], [1,DEF], [3,XYZ]] How can I compare the 2 and return ABC, DEF based on the comparison of all elements in answers to first elements in the list of list?
Dhruv
16

votes
8

answer
1.3k

Views

Is there any pythonic way to find average of specific tuple elements in array?

I want to write this code as pythonic. My real array much bigger than this example. ( 5+10+20+3+2 ) / 5 print(np.mean(array,key=lambda x:x[1])) TypeError: mean() got an unexpected keyword argument 'key' array = [('a', 5) , ('b', 10), ('c', 20), ('d', 3), ('e', 2)] sum = 0 for i in range(len(array)):...
Şevval Kahraman
0

votes
3

answer
25

Views

Determining whether a tuple is a subset of a list of other tuples

I would like to determine whether a given tuple is a subset of a list of other tuples. I have a list of tuples, for examples: list_of_fails = list([[(1,2,3)], [(1,2,5)], [(1,4,3)]]) I would like to determine whether a given tuple is a subset of any of these tuples, for instance the tuple (1,2) The...
JDraper
1

votes
2

answer
177

Views

why can't we have capital letters in tuple variable declaration in scala

Why can't we have Capital letter in a tuple variable, As I create a TestData it throws an error val (trainingData, TestData): Tuple2[RDD[LabeledPoint],RDD[LabeledPoint]] = (splits(0), splits(1))
wctapasadan
1

votes
1

answer
86

Views

c++ add data to a std::vector containing a std::tuple

Below is code that adds elements to a vector containing a std::pair std::vector args_; template inline OperationEntry& setArg(const std::string& name) { args_.push_back({name, typeid(T)}); return *this; } How do I add elements to a vector containing a std::tuple? std::vector args_; template inline...
cherry aldi
1

votes
3

answer
43

Views

Changing version number to single digits python

I have a version number in a file like this: Testing x.x.x.x So I am grabbing it off like this: import re def increment(match): # convert the four matches to integers a,b,c,d = [int(x) for x in match.groups()] # return the replacement string return f'{a}.{b}.{c}.{d}' lines = open('file.txt', 'r').re...
HeelMega
1

votes
2

answer
45

Views

Why am I getting tuples instead of ints when creating an instance of a class? [closed]

I'm working on a little project where I'd like to collect data from MODBUS slaves and put them in a database. I decided to do it in python, because it has some nice modules for handling both MODBUS and mysql. I am very much new to python and wanted to do some testing first, just to warm up and get s...
occamzchainsaw
1

votes
4

answer
68

Views

filtering tuple inside a tuple recursively

i'm trying to figure out how to filter a tuple inside a tuple like so: input>>>filter_tree((1,2,3,4,(1,2,3)),lambda x:x%2==0) output>>> ((2,4,(2)) this is how far I got : def filter_tree(tree,f): if type(tree)!=tuple: return tree return tuple(filter(f,tuple(filter_tree(node,f) for node in tree)))...
Alex K
1

votes
2

answer
22

Views

Add elements of a list at the end of each tuple of a list of tuples

I have a list with some static elements: ['foo', 1, '', 0] And I have a list of tuples: [('val1', 9), ('val2', 'val3'), ('val4', '')] How can I add the elements of a list at the end of each tuple of a list of tuples? Output [ ('val1', 9, 'foo', 1, '', 0), ('val2', 'val3', 'foo', 1, '', 0), ('val4',...
Keaire
1

votes
4

answer
45

Views

Finding the number of lists in a tuple

I have a function that takes two inputs, both tuples, and checks to ensure they are the same size before continuing. I am having issues in trying to calculate the length of each tuple. Examples: tupA = ([1,2,3,4],[11,22,33,44]) tupB = ([1,2],[3,4],[5,6]) tupC = ([1,2,3,4,5,6,7,8,9]) When I take the...
Kyle
1

votes
2

answer
55

Views

Find key, value pair in dict according to second value of tuples using itemgetter() method

I have the following dictonary: inventory = {'apple':(3, 133), 'banana':(9, 407), 'pear':(17, 205), 'orange':(1, 91)} I would like to find key, value pair according to max value of the second element in the tuple so in this case it should return: banana':(9, 407) I know I can get this result using l...
halny
1

votes
4

answer
49

Views

How to convert Tuple to Async Task

I'm doing a small application and I need help, because I do not know where the problem is. I have not been with C # for a long time and I am learning little by little, because all this is leisure form me, no more. I have the following Tuple that is working correctly: private Tuple CheckStatus() { in...
Mendizalea
1

votes
2

answer
667

Views

with tuples and boost.fusion, is there any reason to use struct?

tuples are similar to structs (discussed here: Boost::Tuples vs Structs for return values). it seems that the only advantage is it's more convenient to write struct because it's shorter and by key rather than a number. one can also use fusion map and structs to access by key Boost::Tuples vs Structs...
kirill_igum
1

votes
0

answer
51

Views

Julia traversing the expression tree containing broadcast results in unintended tuples

I am trying to understand Metaprogramming in Julia. I wrote the following code function traversal!(x::Expr,mem) for xx in x.args if isa(xx,Expr) push!(mem,xx) traversal!(xx,mem) end end end expr=:(sum((x-cos(W2*sin(W1*x+b1)+b2))^2)) mem=[] a=traversal!(expr,mem) I expect mem to be :((x - cos(W2 *...
user2741736
1

votes
1

answer
57

Views

Convert string representation of tuple to dict

I have a string representation of tuple as follows: t = '(a,b),(c,d),(e,f)' I want to convert this to dict like this: d = {'a':'b', 'c':'d', 'e':'f'} I tried doing it in following way >>> l = t.split(',') >>> l >>> ['(a', 'b)', '(c', 'd)', '(e', 'f)'] >>> l = [i.replace('(','').replace(')','') for i...
bro-grammer
1

votes
3

answer
102

Views

How to validate the length of nested tuple passed to a function?

I am building a function that accepts the list of tuples. For example: my_list = [ ('str1', 1, 11), ('str2', 2, 22), ('str3', 3, 33), ('str4', 4, 44) ] I want to create a function with definition such that it will ONLY accept the parameters with the size of each nested element as '3'. How can I de...
Tummomoxie
1

votes
0

answer
41

Views

Is there a reason why __all__ variable in __init__.py is defined as a list in Python documentation?

As one may read here - __all__ variable is described as a list. Is there a reason (or does it even matter) for choosing this type over tuple? Both options work but tuple seems to be more valid as immutable type.
Mnich
1

votes
1

answer
89

Views

Using for / list comprehension for creating a tuple from any amount of other tuples

With the following code I'm looking at how to create the TRACKS[0] and ARM[0] tuples (or even a whole set, e.g. ARM), as they are very similar - I think something like a list comprehension would work (as I'm picturing a for each loop). # MOTORS: all, m1, m2, m3, m4, m5 (+, -) MOTORS = ( ( (0b0101010...
zimchaa
1

votes
1

answer
227

Views

Compare array of tuples in swift

I've declared the following for my tuple type: public typealias Http2HeaderTableEntry = (field: String, value: String?) func ==(lhs: [Http2HeaderTableEntry], rhs: [Http2HeaderTableEntry]) -> Bool { guard lhs.count == rhs.count else { return false } for (idx, element) in lhs.enumerated() { guard elem...
Gargoyle
1

votes
0

answer
54

Views

Inserting Batches into Postgres with CDO

So I have the following code that is supposed to batch insert values into Postgres: config const batchsize = 10000; proc bulkInsertSparseMatrix(con:Connection, aTable: string, fromField: string, toField: string, weightField: string, A) { const q = 'INSERT INTO %s (%s, %s, %s) VALUES (%s, %s, %s);';...
Tshimanga
1

votes
2

answer
36

Views

Converting a pandas dataframe to a list of entries

I have a dataframe from a numpy array. matrix = scipy.sparse.rand(5, 3, density=0.2, format='lil') array = numpy.array(matrix.toarray()) users = {5: 0, 10: 1, 15: 2, 20: 3, 25: 4} games = {1: 0, 4: 1, 6: 2} dataframe = pd.DataFrame(data=array, index=users.keys(), columns=games.keys()) What I need n...
maudidi
1

votes
0

answer
49

Views

Are local tuple arguments of a function ever optimized away?

In scala, very often I find myself passing a tuple to a function. For example, as the accumulator element to a collection. The simplest case is: val x = (a,b) def f(x : Tuple[Int, Double]) : Int Will the compiler ever optimize this into def f(a : Int, b : Double) : Int In other words, will locally s...
Luciano
1

votes
0

answer
19

Views

Questions about Tuples

So I was able to run part of a program doing below (using tuples) def reverse_string(): string_in = str(input('Enter a string:')) length = -int(len(string_in)) y = 0 print('The reverse of your string is:') while y != length: print(string_in[y-1], end='') y = y - 1 reverse_string() The output is: En...
markmark1983
1

votes
1

answer
1.1k

Views

Tuple unpacking in lambda function

How should I got about rewriting this lambda to fit Python3 standards? top10_popular = [k for (k, (v1, v2)) in sorted(site_freq_150users.items(), key=lambda (k, (v1, v2)): v2, reverse=True)[:10] I've read that this has to do with the removal of tuple unpacking in Python3, but now I'm sure how to rew...
AdamQadmon
1

votes
0

answer
14

Views

How to use del in tuples

x = 1.0, [2,4,8], 16 4 can be popped out from x[1] by using pop x[1].pop(1) but is there anyway this output can be achieved using del? (1.0, [2, 8], 16)
Muhammad Robiul Alam
1

votes
2

answer
228

Views

Comparing and sorting elements in tuple

I have a vector and I have already sorted the tuple in accending order according to a. The structure is something like this. vect = { 42,324,{}; //[0] 43,231,{}; 45,97 ,{}; 73,32 ,{}; //[1] 112,87,{}; 114,249,{}; //[2] } I am trying to compare 'a' and group them if the difference between elements i...
Syd
1

votes
1

answer
32

Views

What Type Collection Can I Access By Class Type and Return Not Found When Necessary

I apologize for the long, probably confusing title which I will try to clear up. So here's the situation, I have a tuple of vectors of Components (custom classes). Every component has an id which corresponds to it's index in it's respective vector within the tuple. The Components belong to an Entity...
Ryoku
1

votes
3

answer
63

Views

count occurence of value (tuple set) in dictionary keep original dictionary length in output list/dictionary/ tuple

I've seen this sort question asked many times but unfortunately for me this time it comes with a bit of a twist. I have a dictionary in the format: name: (job, score) example: dict = {bob: (farmer, 9), sue: (farmer, 9), tim: (farmer, 5), jill, (chef, 8)} now if i use: x = Counter(x for x in dict.va...
dood
1

votes
2

answer
67

Views

helpd need with sorted tuple and linq query

I've writen a little test case to explain my issue. I'm somehow able to query my DB to get a list of list of tuple. From which I want to extract a list of tuple, with no duplicate, ordered by Item1 ... which is fine, but now I always want to remove tuple when Item2 is not sorted in descending order...
1

votes
2

answer
36

Views

how to sum the values in a list for a key in string datatype while having hyphen as one of value

I have dictionary by the name of temp dict_items([('/history/apollo/', ['6245', '6245', '6245', '6245', '6245', '6245', '6245', '6245']), ('/shuttle/countdown/', ['3985', '3985', '3985', '3985', '3985', '3985', '3985', '-', '-', '-', '0', '3985', '4247', '3985', '3985', '3998', '0', '3985', '3985',...
Hansel Jade
1

votes
1

answer
101

Views

groupByKey of RDD not getting passed through

Have a query regarding groupByKey on my RDD. Below is the query I'm trying: rdd3.map{ case(HandleMaxTuple(col1, col2, col3, col4, col5, col6, col7, col8, col9, col10, col11, col12, col13, col14, col15, col16, col17, col18, col19, col20, col21, col22, col23, col24, col25)) => (HandleMaxTuple(col1,col...
knowone
1

votes
3

answer
298

Views

Change all values of dictionary with tuple keys in python

I am currently trying to change all values in a large dictionary (to the negative). I would like the statement to be in one line. I have the following dictionary sample: dict = {(0,0): 1, (2, 4): 2} What I want is newdict = {(0,0): -1, (2, 4): -2} I first tried several variations newdict = {x: -x fo...
kel
1

votes
1

answer
60

Views

recursive function that iterates through a list of tuples (int * int) and adds the second value

I want to write a function that iterates through a list of tuples (int * int) and adds the second value of the tuple if the first value of the tuple is the int 0. I came up with the following code however, it raises exception for every case, could anyone point out what is the error in the function?...
JackWu
1

votes
0

answer
54

Views

Creating tuples from types list

I have an old code with the following semantic: template void doThings( Columns&& cols ) { // internal cols processing.. } Calling side can be: doThings( boost::fusion::vector_tie ); doThings( boost::fusion::vector_tie ); doThings( boost::fusion::make_tuple()); // etc.. I need to refactor doThings...
1

votes
1

answer
128

Views

Possible create named tuple type using reflection?

I can create a normal tuple type with Tuple.Create or typeof(Tuple).MakeGenericType etc, but how can I make a named tuple? With other property names than Item1, Item2 etc, using reflection in runtime.
Andreas Zita
1

votes
0

answer
29

Views

Where does this timestamp come from? (LED priority signal)

I have this code and it runs two times fine, while on third call I get an error, as if I would have passed Timestamp. I only ever pass Tuple or None. from pprint import pprint from gpiozero import RGBLED def signal(pri, newcolor): signal.priority[pri] = newcolor pprint(signal.priority) try: signal.l...
Jakub M.
1

votes
1

answer
764

Views

Tuple with For-Each loop

I am not sure if I am doing something wrong here or if something is actually wrong. It might totally be an overlook which is why I sent it to community to take a look. I am creating a List of Tuple on client side and returning to WCF via REST JSON. I am getting the value perfectly fine at the server...
Ashutosh Vyas
1

votes
2

answer
49

Views

Create a dataframe using tuples

I have three tuples : x = (1,2,3) y = (4,5,6) z = (7,8,9) I want to create a DataFrame which has a column containing the variable name of the set and another column with the values. Example output: x 1 x 2 x 3 y 4 ... ..
Sharvari Gc
1

votes
2

answer
467

Views

2D lookup table creation in python

How can I create a variable in python Matrix_Table holding value of lookup table like: And also how is it possible to obtain the corresponding value present in (t1,i4)??? Thanks for suggestions
Tomy
0

votes
0

answer
14

Views

How to get the highest 4 tuple values?

I am trying to get the highest 4 values in a list of tuples and put them into a new list. However, if there are two tuples with the same value I want to take the one with the lowest number. The list originally looks like this: [(9, 20), (3, 16), (54, 13), (67, 10), (2, 10)...] And I want the new li...
declac

View additional questions