FAQ Database Discussion Community


Python: method to extract tuple [duplicate]

python,python-3.x,tuples,extract
This question already has an answer here: Expanding tuples into arguments 3 answers I have a tuple of constants: WIN = 640, 360, "Example", False, 'tool' # x, y, title, resizable, style And now to use it I have to type in this: app = pyglet.window.Window(WIN[0], WIN[1], WIN[2], WIN[3],...

Why does assigning to an empty list (e.g. [] = “”) raise no error?

python,string,list,tuples
In python 3.4, I am typing [] = "" and it works fine, no Exception is raised. Though of course [] is not equal to "" afterwards. [] = () also works fine. "" = [] raises an exception as expected though, () = "" raises an exception as expected...

Python: for each tuple in list, check if string in tuple

python,list,tuples
I know how to cycle through all tuples in a list. However, my problem is to see if a string is in a tuple within the list. I have constructed the following: # where: unformatted_returns = [('2015-6-10', u'88.48'), ('2015-6-9', u'86.73'), ('2015-6-8', u'86.15'), ('2015-6-5', u'86.05')] date_new = '2015-6-8' for n in...

Scala list pattern matching in value declaration

list,scala,pattern-matching,tuples
Assuming the following list of four tuples: > def getList = List( (1,2), (3,4), (5,6), (7,8) ) I want to parse it into three sections in new values declaration like this - the last tuple (l1,l2), the penultimate tuple (p1,p2) and the rest of the list rest. Moreover, I'd like...

Python: tuple assignment while at same time converting type

python,floating-point,type-conversion,tuples
I'm reading tab separated values from strings into an object like this: class Node(rect): def __init__(self, line): (self.id, self.x1, self.y1, self.x2, self.y2) = line.split('\t') That works fine, but say I want to convert those x and y coordinates, which are read from the string line, to floats. What is the...

How get value of a list by a tuple in Django

python,django,dictionary,tuples
I have this structure in a tag called items_value: { ('prog1','date1'): { 'total_error': 4256, 'components1': [{ 'errors': 5, 'lines': 1 }], 'components2': [{ 'errors': 5, 'lines': 1 } ], ('prog2','date2'): { 'total_error': 4256, 'components1': [{ 'errors': 5, 'lines': 1 } ] } How a get the values inside each tuple...

How to iterate through two lists in parallel with one list randomized

list,python-2.7,iteration,tuples
This thread explained how to iterate through two parallel lists. When I apply that lesson to a shuffled list, however, I get the following error: "zip argument #2 does not support iteration." Why does a shuffled list not support iteration? How else can I randomize the order of answer choices?...

SML - Unzip tuples in one list

list,tuples,sml,unzip
I need to "unzip" a list of tuples and even though I tried with the unzip function it doesn't do what I want to. In fact, as I understood the unzip function returns you a tuple of list, but what i want is this. Giving a list of tuple like...

Expanding tuples in list comprehension generator

python,tuples
I am using this function def convert_tuple(self, listobj, fields=['start', 'end', 'user']): return [(getattr(obj, field) for field in fields) for obj in listobj] My desired output which I want should be [('2am', '5am', 'john'), ('3am', '5am', 'john1'), ('3am', '5am', 'john2') ] The output of above function is [genexp, genexp, genexp] Its...

How to divide a tuple into two in pythonic way

python,python-2.7,tuples,list-comprehension
I got a problem which is: receive a tuple with objects of any type, and separate it into two tuples: the first, with strings only; the second, with numbers only. Alright. The standard algorithm would be something like: def separate(input_tuple): return_tuple = ([],[]) for value in input_tuple: if isinstance(value, str):...

converting string to tuple in python

python,string,tuples,eval
I have a string returnd from a software like "('mono')" from that I needed to convert string to tuple . that I was thinking using ast.literal_eval("('mono')") but it is saying malformed string....

Extend a Show instance to a Tuple of any size

haskell,tuples,instance
I want to create a new type of data with Haskell and create the related Show instances. I need to create the tuple Show instance with another delimiter than ,. I implemented this code (with the {-# LANGUAGE FlexibleInstances #-} pragma): newtype Data = Data Double instance Show Data where...

Creating numbered list of output

python,list,sorting,python-3.x,tuples
How can I edit my code such that my output: the 8512 and 7759 i 6182 to 6027 a 4716 of 4619 he 2873 in 2846 you 2777 was 2457 becomes 1. the 8512 2. and 7759 3. i 6182 4. to 6027 5. a 4716 6. of 4619 7....

Values accepted in a tuple in swift

swift,tuples
I am a completely newbie in swift and in functional Programming. My silly question is the following: Can a tuple return a set of functions? Is it a function like that accepted? someFunction(param: Bool) -> ((Int) -> Int, (Float) ->Float) -> Double) Thanks for your reply...

How to add an element to a tuple in a list in haskell?

list,haskell,tuples
I have the following types and database:- type Title = String type Singer = [String] type Year = Int type Fan = String type Fans = [Fan] type Song = (Title, Signer, Year, Fans) type Database = [Song] songDatabase :: Database songDatabase = [("Wrapped up", ["Olly Murs"], 2014, ["Garry", "Dave",...

Return all items at once from class to form using tuple c#

c#,winforms,tuples
I created class in which I do calculations. I send data from my windows form, do the calculation and return values again to my form using tuple with 3 values. I did that but returning only 1 item at a time. When it get to second item it goes again...

Convert list of lists to custom dictionary

python,list,dictionary,tuples
I'm unsuccessfully trying to convert list of lists to a custom dictionary. I've created the following output saved in two lists: headers = ['CPU', 'name', 'id', 'cused', 'callc', 'mused', 'mallc'] result = [['1/0', 'aaa', '10', '0.1', '15', '10.73', '16.00'], ['1/0', 'bbb', '10', '0.1', '20', '11.27', '14.00'], ['1/0', 'ccc', '10', '0.2',...

Haskell - Printing a list of tuples

list,haskell,tuples
I have a list of tuples in the form: [(String, Int)] How can I print this to display like: String : Int String : Int String : Int ... I am very new to Haskell so please make it as clear as possible. Thank you! Update: Here's how the code...

List of lists with tuples to list of lists

python,list,tuples
I have a list of lists that looks like the following: a = [['he', 'goes'], ['he does'], ['one time'], [('he','is'), ('she', 'went'), ('they', 'are')], ['he', 'must'], ['they use']] I trying to to flatten the list so that it is only a list of lists with no tuples. For example: a...

Python - Write list of tuples horizontally to a text file

python,list,file,tuples
I have a list of tuples as follows: listo = [ (A,1),(B,2),(C,3) ] I want to write this list to a file as below: A B C 1 2 3 I tried the following and it gave the output as below: with open('outout.txt', 'w') as f: for x, y in...

call back in python Tic Tac Toe code

python,tuples,tic-tac-toe
so I have this code right here for a tic tac toe program def playerID(): # asks player if want x or y letter = '' while not (letter == 'X' or letter == 'O'): letter = input('Do you want to be X or O?').upper() # first tuple is player,...

Loop through list tuples and add if there is no match

c#,list,loops,tuples
i am writing a game server in C#,every time someone sends the login message with his username i add him to a list of tuples with ID,IPENDPOINT,USERNAME. I want to check if the client doesn't have same username as an already connected client,so i tried to loop through the list...

'tuple' object has no attribute 'rstrip'

python,django,tuples
i got this problem : 'tuple' object has no attribute 'rstrip' my script is : def destroyVM(request,id): conn = sqlite3.connect('testDB') c = conn.cursor() api = 'http://196.203.216.18:5555/client/api' apikey = '3U7UPLR4JHYEzOhKe0JYnR_ICChdmuynnl0SdqmFzFgG4Hgd6BJHHjcSk2K3SsXUvheLEoN-SlRuEOpqZbqbVA' secret = 'JU1gQk99VpAEZWWKxiR97w8mIPtSZsXwuORL6H2NKkve0EHDvBZ5IQN-CXHqMhVKmOLRcRhjyr4RPnTqAmD5Ig' cloudstack = CloudStack.Client(api, apikey, secret) # ouvrir une connexion serveur/client c.execute("SELECT vmid FROM vmm_vm where id ="+id+";");...

Is it possible to turn a list in Haskell into a string of the elemnts within?

list,haskell,tuples
I have a small film "database" which is just a list and each element in the list is a tuple. I would like to display the list in a string as an easy to read format so for example each data item in the list should be displayed as follows:...

Python - Add a tuple to an existing list of tuples in a specific position

python,list,python-2.7,tuples
Suppose I have a list of tuples as follows: listA = [ (B,2), (C,3), (D,4) ] I would like to add another tuple (E,1) to this list. How can I do this? And more specifically, I would like to add this tuple as the 1st tuple in the list so...

List of tuple. Comma instead of point in double values

c#,list,tuples,comma
The situation: I have a list of tuple, in which a tuple is added: List<Tuple<double, double>> list = new List<Tuple<double, double>>(); list .Add(new Tuple<double, double>(2.2, 6.6)); All seems to be ok. But... In Debugging mode, in the list of local vars I see next: [0] {(2,2, 6,6)} System.Tuple<double,double> By the...

Sorting a list of list of tuples

python,list,python-2.7,sorting,tuples
I am trying to sort a list of list of tuples based on the values in the last tuple. [[(3, 1005), (3, 1050), (3, 945), (4, 1510), (13, 4510)], [(3, 1000), (3, 955), (4, 1501), (5, 1900), (15, 5356)], [(3, 945), (3, 955), (3, 901), (5, 1900), (14, 4701)], [(3,...

Inserting tuples in a list Ocaml

list,tuples,ocaml,concatenation
I have declared a list l=[];; and now trying to append tuples into this list using '@'. But I am not able to do so. Can anyone please help me sorting this out. let l = [] for x = 1 to 10 do l <- [email protected][(x,x+10)] done;; And want...

Passing a condition into Func of a Tuple>

c#,properties,tuples
I am trying to create a list of tuples with properties and conditions for their validation. So I had this idea in mind: List<Tuple<string, string, Func<bool>>> properties = new List<Tuple<string, string, Func<bool>>> { Tuple.Create(FirstName, "User first name is required", ???), }; ... How can I pass expression of type (FirstName...

Summing Python Tuple Subsets ((1,john), (2, joey))=(3, john + joey)

python,tuples
I am trying to add all the tuples inside a subset together. so far I have: list(itertools.combinations(((1, 'aa'), (2, 'bb'), (3, 'cc'), (4, 'dd'), (5, 'ee'), (6, 'ff'), (7, 'gg'), (8, 'hh')), 6)) which produces: ((1, 'aa'), (2, 'bb'), (5, 'ee'), (6, 'ff'), (7, 'gg'), (8, 'hh')), ((1, 'aa'), (3,...

Tuple indexing and printing

python,list,printing,tuples
Python beginner here and a little confused with tuples when working with them as lists. I have the code below and to my understanding the peek function should return the first tuple pair but in reality it returns only the first word of that pair. Why is this?? Thanks in...

Java Tuple Without Creating Multiple Type Parameters

java,tuples
Is there any way to create a Tuple in Java, without having to create multiple classes? For example, it is possible to make a different class for every different type of Tuple, each with a different number of Type Parameters: public class SingleTuple<T>{} public class DoubleTuple<T1, T2>{} public class TripleTuple<T1,...

Find the index of a list of tuples with nondistinct values in first index of tuple

python,list,tuples
I'm trying to get the index of a list of 2-tuples in Python, where the 0 index of each tuple is 'a': list_of_tuples = [('a', 1), ('a', 2), ('a', 3)] So I use the following list comprehension to try to find out which index is returned, correct? index_list = [x...

namespace std overloading less than

c++,c++11,tuples,std
I was curious about why this piece of code doesn't work: #include "stdafx.h" #include <iostream> #include <tuple> #include <string> #include <vector> #include <algorithm> typedef std::tuple<int, std::string> intString; bool operator<(intString& lhs, intString& rhs){ return std::tie(std::get<1>(lhs), std::get<0>(lhs)) < std::tie(std::get<1>(rhs), std::get<0>(rhs)); } void printIntStrings(std::vector<intString>& v){ for (intString& i : v){ std::cout <<...

Cartesian (outer) product of lists in OCaml

list,polymorphism,tuples,ocaml
I would like to iterate over all combinations of elements from a certain number of lists which have the same length but not necessarily the same type. First I tried to write a general cartesian (outer) product function which takes a list of lists and returns a list of tuples,...

Python: Sorting Tuples in array based off first element

python,arrays,sorting,file-io,tuples
I had a file with records (highscores) stored as an int on each line (with a header). In my python project I was reading the records into an array, then adding a record (just an int), sorting the array (with the new record added) and then overwriting the file with...

What does this lambda function do

python,dictionary,tuples
I was looking through the questions of sorting dictionary by values in python and came across this answer. sorted(d.items(), key=lambda x: x[1]) However, i do not understand what this function exactly does and how does it even help to sort the dictionary by returning a list of tuples or anything...

Passing tuple to a Python function

python,tuples
I know that there has been a bit of discussion about passing a tuple to a function; I checked all of them but couldn't solve my problem. So here is the problem. I am trying to pass two tuples into a function and do calculations on them. Here is a...

Python 2.7 Removing Duplicate Elements in a List of Lists compared to another List of Lists

python,list,python-2.7,tuples
I am trying to take two List of Lists and compare them against each other. From my research the closest I have found was this How to compare a list of lists/sets in python?. I am trying to do something just slightly different and may be heading down the wrong...

F# when should you use tuple and when should you use struct? [closed]

struct,f#,tuples,containers
What are the underlying differences between F# tuples and structs. They can both hold multiple variables, but I just want to know when one is used over the other. To be more specific, I am trying to pass a bunch of parameters through a bunch of functions with a new...

How to print a type vector> to screen c++?

c++,vector,tuples,std
Let's say I have std::vector<std::tuple<string ,int ,int>> tupleVector; tupleVector.push_back(std::tuple<string ,int ,int>("Joe", 2, 3)); tupleVector.push_back(std::tuple<string ,int ,int>("Bob", 4, 5)); How can I iterate on the vector to print all values of this vector containing a tuple?...

List of tuples from heirarchical nested lists

python,list,nested,tuples
Having an outer list of inner elements, each said inner element being a flat/nested list. Each said inner list has a nesting structure that matches the inner list in the preceding outer cell. Meaning that each primitive value in a list either corresponds to a primitive value or to a...

Zipping same value over a list of tuples Haskell

list,haskell,tuples
I would like to transform the following tuple list a = [(1,()),(2,())] into a nested tuple list by the same value b = [(False,(1,())),(False,(2,()))] Using the zip function in this format zip [False] a only gives me [(False,(1,()))] Any suggestions or advice would be much appreciated....

Subtuples of a tuple [duplicate]

python,tuples
This question already has an answer here: Getting the subsets of a set in Python 6 answers How do I generate [(0,), (1,), (2,), (0,1), (0,2), (1,2), (0,1,2)] programmatically (that is, without writing everything out by hand)? That is, a list of all nonempty subtuples of the tuple (0,1,2)....

C++11 way to index tuple at runtime without using switch

c++,c++11,tuples
I have a piece of c++11 code similar like below: switch(var) { case 1: dosomething(std::get<1>(tuple)); case 2: dosomething(std::get<2>(tuple)); ... } Is there any way to remove this large switch ? Note that get<var> does not work because var is not constant, but I know var is in small range i.e....

Lists, Tuples, and Statistics Program Try-Except Block Error

python,list,error-handling,tuples,try-except
I am working on a Lists, Tuples, and Statistics Program for my intro class, and am having some difficulty with a try-except block. The program we are supposed to make is supposed to ask for the user to name a file to input, and then give some information about the...

Python, to pick specific elements from a list of tuples

python,list,tuples
Hello all…I have a list of tuples (number of colors in an image. For example, there are 6320 (255, 255, 255) colors there etc.) What I want to have is get the number of certain colors, like “(159, 177, 205)” and “(223, 213, 196)”. 2 and 618 are their correspondences....

Appending Tuples to an Array of Tuples?

arrays,swift,tuples
I'm trying to make an array of tuples to store the data of a to-do-list app but can't figure out how to append the tuples to the array. Here is my code: First, the array was declared globally: var eventList : [(name: String, date: String)] = [] Here's the code...

Get numpy array from an array of tuples

python,arrays,numpy,tuples,mysql-python
I was using numpy, MySQLbb and scipy and ended up with an array of tuples from a MySQL cursor execution. Then I used np.fromiter. Now I have an array of tuples that looks like this: >>> A array([('bob', 0.43), ('dan', 0.24), ('bill', 0.14) ('sharen', 0.28), ..., ('zena', 0.24), ('zoe', 0.39)],...

List of tuples from (a, all b) to (b, all a)

python,list,python-2.7,tuples
I am starting with a list of tuples (a,all b). I want to end with a list of tuples (b,all a). For example: FROM (a1,[b1,b2,b3]) (a2,[b2]) (a3,[b1,b2]) TO (b1,[a1,a3]) (b2[a1,a2,a3]) (b3,[a1] How do I do this using Python 2? Thank you for your help....

tuple() not working fully with files in python

python,tuples
So i am trying to copy all the lines present in a file into a list. From a previous question on here I found out this method of copying all the lines into a list.The problem I am facing is that not all the contents of the file are getting...

Can't edit a tuple from inside a function [closed]

python,tuples
I am programming an application in python. Here is the function: def aircraftListBoxRefresh(): sqlConnect=sqlite3.connect("fglconfdb") sqlCursor=sqlConnect.cursor() sqlCursor.execute("SELECT fgAircraftDir FROM fglconfig") adl=sqlCursor.fetchall() global aircraftDirectories for x in adl: aircraftDirectories=aircraftDirectories+(x,) I put print(aircraftDirectories) to test whether the value changes. It changes in side the function. But outside the function it is null. I...

Is it possible to index nested lists using tuples in python?

python,tuples,nested-lists
I just started with python and very soon wondered if indexing a nested list with a tuple was possible. Something like: elements[(1,1)] One example where I wanted to do that was something similar to the code below in which I save some positions of the matrix that I will later...

Sum values in tuple (values in dict) Python 2.7

python,python-2.7,dictionary,tuples
I have a dictionary data that looks like that with sample values: defaultdict(<type 'list'>, {(None, 2014): [(5, 1), (10, 2)], (u'Middle', 2014): [(6, 2), (11, 3)], (u'SouthWest', 2015): [(7,3), (12, 4)]}) I get this from collections.defaultdict(list) because my keys have to be lists. My goal is to get a new...

std::vector of std::tuples leads to unknown size

c++11,vector,visual-studio-2013,tuples
I want to store three arbitrary ints inside a std::vector without defining a struct/class. So I went for std::tuple<>: std::vector<std::tuple<unsigned int, unsigned int, unsigned int> Using MS VS 2013, it leads to the following error: >c:\program files (x86)\microsoft visual studio 12.0\vc\include\vector(1628): error C2036: 'std::tuple<unsigned int,unsigned int,unsigned int> *' : unknown...

Python Tuple text string output

python,mysql,tuples
I am writing a sensor alert script and am trying to perfect the dynamic messages. The script spits out a different customized message depending on the sensor that sends the message. The values come from a MySql database. Here are the mysql values: CustomerID = efed3a47 Sensor = Dining Room...

Zip with tuples and list

python,string,list,zip,tuples
I need to write a code that will return the characters of two strings as a list of tuples. The code should stop when either one of the strings runs out of characters. I know is a simple code but I cannot get to work where it gives me more...

Array to tuple conversion python [duplicate]

python,arrays,tuples,data-conversion
This question already has an answer here: Create (L[i], L[i+1]) tuple list from list L [duplicate] 4 answers I have an array that looks like this [1,2,3,4,5] and I would like a list of tuples that looks like this: [(1,2),(2,3),(3,4),(4,5)] What is the most convenient way to do this...

Problems mixing Arrays, Tuples and Closures in Swift [duplicate]

arrays,swift,closures,tuples
This question already has an answer here: Array of tuples in Swift 3 answers I am trying to manage an array of (String, closure) tuples. The array is defined as: var menuItems: [(title: String, closure: () -> Void)] = [] Now I'm trying to add items to it: //...

Sum third value in tuple for a given pair of the first two values in the tuple using Python

python,tuples
the question I have is related to the "Sum second value in tuple for each given first value in tuples using Python" and the "How do I sum the first value in each tuple in a list of tuples in Python?" topic, but I was not able to extract the...

How to apply a dict in python to a string as opposed to a single letter

python,list,dictionary,tuples,alphabet
I am trying to output the alphabetical values of a user entered string, I have created a dict and this process works, but only with one letter. If I try entering more than one letter, it returns a KeyError: (string I entered) If I try creating a list of the...

How to return a value from tuple

python,list,for-loop,while-loop,tuples
Okay, so say I have a tuple like this values = ('1', 'cat', '2', 'bat', '3', 'rat', '4', 'hat', '5', 'sat') What loop function would I have to write to ask for a user input for the integer and have it return the word. ie. user inputs 1 and it...

comparing list of tuple elements python

python,list,tuples
I have a two list of tuples t1 = [ ('a',3,4), ('b',3,4), ('c',4,5) ] t2 = [ ('a',4,6), ('c',3,4), ('b',3,6), ('d',4,5) ] Such that the order of the tuples may not be the same order and the lists may not contain the same amount of tuple elements. My goal is...

Merge items of two lists into list of tuples that also contains index

python,list,tuples
What would be the most pythonic way of achieving the following: list_a = ["A", "B", "C"] list_b = ["X", "Y", "Z"] idx_start = 100 result = [ (100, "A", "X"), (101, "B", "Y"), (102, "C", "Z") ] The lists are guaranteed to be of the same size....

Custom class as AnyObject in tuple

swift,tuples
I'd like to use AnyObject in a tuple in order to pass on my custom class: var array: [(Float, AnyObject)] = [] let number: Float = 10.0 let instance = MyClass() Both ways of adding a tuple to the array do not work: array += [(number, instance)] array.append((number, instance)) Is...

Python converting a tuple (of strings) of unknown length into a list of strings

python,string,tuples
I have a recursive tuple of strings that looks like this: ('text', ('othertext', ('moretext', ('yetmoretext')))) (it's actually a tuple of tuples of strings - it's constructed recursively) And I'd like to flatten it into a list of strings, whereby foo[1] would contain "text", foo[2] "othertext" and so forth. How do...

Combine two lists of tuples by key

python,list,tuples
I have two lists of two elements tuples. First element of tuple is ID and second is some kind of value. Type of value depends on list. lst1 = [ ('a', 1), ('b', 2), ('c', 3) ] lst2 = [ ('b', 5), ('a', 4), ('c', 6) ] What is the...

Only select dictionary keys that are tuples?

python,dictionary,tuples
I have a dictionary with both string and 2-tuple keys. I want to convert all the 2-tuple keys from (x,y) to strings that are x:y. Here is my data: In [4]: data = {('category1', 'category2'): {'numeric_float1': {('Green', 'Car'): 0.51376354561039017,('Red', 'Plane'): 0.42304110216698415,('Yellow', 'Boat'): 0.56792298947973241}}} data Out[4]: {('category1', 'category2'): {'numeric_float1': {('Green', 'Car'):...

Iteration Through tuple of dictionaries in Python

python,list,loops,dictionary,tuples
I am trying to iterate through a tuple of dictionaries using Python, get the value that I'm looking for and then modify another dictionary with that value. Example: Dict = {'1': 'one', '2': 'three'} Tuple = ({'1': 'one', '5': 'five'}, {'4': 'four', '2': 'two'}) My goal is to modify Dict...

Working with tuples in C#

c#,tuples
I have the following code working with Tuples. Input is list of items, output is list of tuples and we need to calculate number of items for each date basically. List<Tuple<DateTime, int>> list = new List<Tuple<DateTime, int>>(); foreach (ItemClass item in items) { foreach(Tuple<DateTime, int> tuple in list) { if...

create variable for one tuple item at the end of a list

python,list,tuples
I have a list of tuples called list_cs: ('2015-05-14', 685) ('2015-04-15', 680) ('2015-03-20', 675) ('2015-02-11', 680) ('2015-01-13', 685) ('2014-12-10', 685) ('2014-11-25', 685) ('2014-10-09', 685) ('2014-09-15', 690) ('2014-08-21', 680) ('2014-07-22', 680) For the first 5 tuples, I want to assign the scores in the second position of the tuple to unique...

Create an optional tuple

c++,boost,tuples,variadic-templates,optional
I don't understand why there is no optional tuple, and I mean by that, something like this ; optional<int,string,char> that would combine an optional int, optional string and optional char. You can think of it like an optimized std::tuple<boost::optional<T>...> where the booleans used by the optionals would be all together...

Python compare tuples with different data types but same values

python,comparison,tuples
I am trying to compare two tuples to determine if there is any difference. The code I use is not solving my problem because I do not care about if value has different types. In the example I do not care if value "1" is string or integer. I would...

Datastructure choice issue

python,list,python-2.7,data-structures,tuples
I'm new to python. I need a datastructure to contain a tuple of two elements: date and file path. I need to be able to change their values from time to time, hence I'm not sure a tuple is a good idea as it is immutable, and every time I...

How can I write a file of tuples?

python,list,sorting,tuples
Im trying to get to write a list of tuples into a file and then organise them in Value and lowest to highest, but I always get the same error. Is there any way this can be done? Here is my code: name = input("Please enter your name: ") class_name...

Create Python string placeholder (%s) n times

string,list,python-2.7,tuples,placeholder
I am looking to automatically generate the following string in Python 2.7 using a loop based on the number of columns in a Pandas DataFrame: INSERT INTO table_name (firstname, lastname) VALUES (534737, 100.115) This assumes that the DataFrame has 2 columns. Here is what I have: # Generate test numbers...

Does GCC optimize std::tie used only for readability?

c++,c++11,optimization,tuples,tie
Suppose I have a std::tuple: std::tuple<int,int,int,int> t = {1,2,3,4}; and I want to use std::tie just for readability purpose like that: int a, b, c, d; // in real context these names would be meaningful std::tie(a, b, c, d) = t; vs. just using t.get<int>(0), etc. Would a GCC optimize...

python json dump writability “not write able”

python,string,python-3.x,tuples,stringio
So this is the second piece of a problem with my program, but a completely different issue, thanks to the helpful person who suggested JSON as a better method to do what I wanted.... Anyway... some success with JSON. The program also changed theme, I definitely am not tying to...

Trouble with Tuples

python,oop,tuples
I'm doing some OOP in Python and I'm having trouble when the user inputs a tuple as one of the arguments. Here's the code: class Height: def __init__(self,ft,inch=0): if isinstance(ft,tuple): self.feet = ft self.inches = inch elif isinstance(ft,int): self.feet = ft // 12 self.inches = ft % 12 def __str__(self):...

Python `dict` indexed by tuple: Getting a slice of the pie

python,dictionary,indexing,tuples
Let's say I have my_dict = { ("airport", "London"): "Heathrow", ("airport", "Tokyo"): "Narita", ("hipsters", "London"): "Soho" } What is an efficient (no scanning of all keys), yet elegant way to get all airports out of this dictionary, i.e. expected output ["Heathrow", "Narita"]. In databases that can index by tuples, it's...

REST service doesn't return a tuple correctly

c#,rest,tuples,dotnet-httpclient
I have REST service from which I want to return a tuple. The tuples will be 2 lists. See the code below. The GetRecords method returns the tuple and when I inspect the result variable I can see that everything that I require is there and correct. public HttpResponseMessage GetRecords([FromUri]...

convert tuple keys of dict into a new dict

python,dictionary,tuples
I have a dict like this: { ('America', 25, 'm', 'IT'): 10000, ('America', 22, 'm', 'IT'): 8999, ('Japan', 24, 'f', 'IT'): 9999, ('Japan', 23, 'f', 'IT'): 9000 } Now, I want to get all result with key ('America', 'm', 'IT'), in this example. In the above, that would be: {25:...

Replace a list slice with a packed tuple

python,list,tuples,slice
I have a list of points in the form of tuples: myList = [(1,1), (2,2), (3,3), (4,4), (5,5)] I want to replace a slice of variable length with a new tuple (6,6) so the result is something like: myList = [(1,1), (6,6), (5,5)] I tried assigning the tuple to the...

How to add tuples to list after reading from a text file in Haskell

list,haskell,tuples,readfile
I am trying to create a program in Haskell that reads text from a text file and adds them to a list. My idea is: type x = [(String, Integer)] where the String is each word from the text and Integer is how many times that word occurs in the...

Tuples as Key in Map, how to retrieve value?

scala,tuples
Imagine the following (pseudo) class: class Board(rows: Int, cols: Int) { val fields = Map[(Int, Int), Field] // Position is a tuple def getField(position: (Int, Int)): Field { fields(position) } } How could I do this? I could create a type like: type Position = (Int, Int) and then val...

tuple as key to a dictionary says: 'tuple' object does not support item assignment

python,dictionary,tuples
I have this function in python: def initialize(s,cfg): pi={}, for i,w in enumerate(s): j=i+1 for X,rhs in cfg.items(): if rhs.has_key(w): print (j,j,X),rhs[w] pi[(j,j,X)]=rhs[w] return pi and when run I get pi[(j,j,X)]=rhs[w] TypeError: 'tuple' object does not support item assignment The print above it returns (1, 1, 'DT') 1.0 I must...

Python “TypeError: %d format: a number is required, not tuple” [closed]

python,tuples,addition
#PROGRAM BEGINS x = raw_input("Give me the first number:" ), y = raw_input("Give me the second number:" ), print "The addition of %d and %d is %d" % (x, y, x+y) I don't know why it isn't working, please help....

How to get a list of sub tuple if given some indexes of tuple in python?

python,list,tuples
There is a list of tuple like l = [(1, 2, 'a', 'b'), (3, 4, 'c', 'd'), (5, 6, 'e', 'f')] I can use [(i[0], i[2], i[3]) for i in l] to get the result [(1, 'a', 'b'), (3, 'c', 'd'), (5, 'e', 'f')] But if given a variable list...

Swift: Access tuples by subscript

swift,tuples
Let's say I have this code: let tuples = ("1", 2, "3", "4", "5", "6", "7", false) func tableView(tableView:NSTableView, viewForTableColumn tableColumn:NSTableColumn?, row:Int) -> NSView? { let valueForView = tuples[row] } Is there any way to access tuples by subscript?...

Is there any scala library that treat tuples as monads

scala,tuples,monads
Is there any scala library that enriches basic scala tuples with monad syntax. Something similar to the Writer monad but adjusted for usage with tuples. What I look for: val pair = (2, "as") pair >>= (a => point(a+1)) should equal to (3, "as"). As well as for (p <-...

Comparing values of parts of two tuples in python

python,tuples
Here is a simple code I have: a=(6,3,4,5) b=(1,2,1,3) if (a[i]<b[i+1] for i in range(1,3)): print("Yes") else: print("No") what I am trying to do is print Yes if a[1] < b[2] and a[2] < a[3], otherwise return No. This code always returns Yes. Any hint on how to modify this?...

retrieving string from file in python and changing tuples

python,string,python-3.x,tuples,stringio
I have a serious snag in my programming, and it might be an easy fix, but anytime I find something that looks like the right forum post, it's not quite right. I'm using a file to store data created from one part of my program, like a high score, number...

Python list append to list “AttributeError: 'tuple' object has no attribute 'append'”

python,list,split,append,tuples
Alright so I know you cannot append a tuple to a list. However I am still receiving this error despite my best efforts. Can someone tell me what I am doing wrong or what is going on? Traceback (most recent call last): File "C:/Users/.py", line 31, in listRow.append(convertedList) AttributeError: 'tuple'...

How do i sort a dictionary by value that has tuples as values

python,python-2.7,sorting,dictionary,tuples
I have a dictionary that has strings as keys and tuples with two elements as values: d = {"Alex": (18, 22), "Maria": (5, 11), "John": (18, 19), "Jim": (5, 8)} I am trying to sort this dictionary by value but I want a descending order of value[0] and an ascending...

Haskell length toInteger Conversion

haskell,integer,int,type-conversion,tuples
I have the following pair of Integers: maxCollatz :: (Integer, Integer) maxCollatz = (head $ maximum (map collatzList [1..500]), length $ maximum (map collatzList [1..500])) Since I am a newbie, I don't know how to use either fromIntegral or toInteger to convert length to Integer. I know that length must...

Scala Function.tupled vs f.tupled

scala,functional-programming,tuples,flatmap
I have the following Scala code: def f(x: Int, y: Int): Option[String] = x*y match { case 0 => None case n => Some(n.toString) } val data = List((0, 1), (1, 0), (2, 3), (4, -1)) data flatMap {case (x, y) => f(x, y)} But, the last line is too...

Dictionary value in Dictionary list created from tuple doesn't update correctly

python,python-3.x,dictionary,iteration,tuples
When I create a new dictionary value on a dictionary in a list (which was created from a tuple), the dictionary value updates all similar dictionary entries, rather than the single one i wanted: import itertools import random seq = [{'Item': 'A'}, {'Item': 'B'}, {'Item': 'C'}, {'Item': 'D'}] # Create...

How to pass tuple1 if … else tuple2 to str.format?

python,tuples,string-formatting
Put simply, why do I get the following error? >>> yes = True >>> 'no [{0}] yes [{1}]'.format((" ", "x") if yes else ("x", " ")) Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: tuple index out of range I use python 2.6....

Getting unique tuples out of a python set

python,python-2.7,set,tuples,unique
I currently have a set like the following: {(a,b), (b,a), (c,b), (b,c)} What I Would like to have is: {(a,b), (c,b)} As you may notice the duplicate values have been removed completely so that two tuples never have the same elements inside regardless of order. How can I tell the...

How to optimize a list search in SML/NJ?

arrays,list,tuples,time-complexity,sml
I am writing a piece of code in SML/NJ and need, at some point, to access a list, which I have already created. I know that, in C, for example, accessing an array takes constant time. So, I thought that that would be the case for ML as well. Apparently,...