How to easily initialize a list of Tuples?
c# 7.0 lets you do this:
var tupleList = new List<(int, string)>
{
(1, "cow"),
(5, "chickens"),
(1, "airplane")
};
If you don't need a List
, but just an array, you can do:
var tupleList = new(int, string)[]
{
(1, "cow"),
(5, "chickens"),
(1, "airplane")
};
And if you don't like "Item1" and "Item2", you can do:
var tupleList = new List<(int Index, string Name)>
{
(1, "cow"),
(5, "chickens"),
(1, "airplane")
};
or for an array:
var tupleList = new (int Index, string Name)[]
{
(1, "cow"),
(5, "chickens"),
(1, "airplane")
};
which lets you do: tupleList[0].Index
and tupleList[0].Name
Framework 4.6.2 and below
You must install System.ValueTuple
from the Nuget Package Manager.
Framework 4.7 and above
It is built into the framework. Do not install System.ValueTuple
. In fact, remove it and delete it from the bin directory.
note: In real life, I wouldn't be able to choose between cow, chickens or airplane. I would be really torn.
How should I initialize my list of tuples
To create a value of a record type (because it is a record type and not a tuple, a tuple doesn't name its arguments), the syntax is the following:
{ valeur = "Some string" ; nombre = 13 }
If this syntax is too heavy for you, a common practice is to write a builder function:
let mk_vote valeur nombre = { valeur ; nombre }
Here I'm using another piece of syntax to instantiate a record value without using the =
symbol. In that case, it's the same as writing valeur = valeur
and nombre = nombre
.
You can then write:
let votes = [ mk_vote "oui" 120 ; mk_vote "non" 18 ; mk_vote "blanc" 20 ; mk_vote "oui" 20 ; mk_vote "non" 24 ; mk_vote "blanc" 25 ]
let mk_vote (valeur, nombre) = { valeur ; nombre }
would work as well and let you write
let votes = List.map mk_vote [("oui",120);("non",18);("blanc",20);("oui",20);("non",24);("blanc",25)]
For some vote
of the record type you can access the fields with vote.valeur
and vote.nombre
.
You can also use pattern-matching:
match vote with
| { valeur = v ; nombre = n } => (* ... *)
You can also make a record value from another one like so:
let vote = { valeur = "Some string" ; nombre = 13 } in
let vote' = { vote with valeur = "Some other string" } in
(* ... *)
Then vote'.valeur
is "Some other string"
while vote'.nombre
is vote.nombre
,
or 13
in that case.
Finally I couldn't help but notice you were using strings to represent different kind of votes, since there seem to be only three cases, a dedicated type would be more relevant (you are using ocaml after all which lets you handle data properly).
type vote_kind =
| Yes
| No
| Blank
type t_votes = {
value : vote_kind ;
amount : int ;
}
How to initialize a tuple containing an list of expressions in Rascal
The plain answer is that you have to choose a Statement
type like this:
result = <[], empty()>; // using the empty statement as a default
Note how I did not use a type (it can be inferred)
You could also write it with a type:
tuple[list[Expression],Statement] result = <[], empty()>;
There are other ways though to write this code, which you might find interesting.
The \for
constructor itself, can replace the concept of the tuple you required. You can later project out its fields using myForLoop.initializers
(for example):
Statement findFirstForStatement(loc project) {
decls = createAstsFromFiles(files, false);
visit(decls) {
case f:\for(_,_,_,_): return f;
}
return empty();
}
rascal>ff = findFirstForStatement(pr);
Statement: for(....)
rascal>ff.initializers
list[Expression]: [...]
Or you can use a Maybe:
import util::Maybe;
Maybe[tuple[list[Expression], Statement]] findFirstForLoop(loc project) {
decls = createAstsFromFiles(files, false);
visit(decls) {
case f:\for(_,_,_,_) : return just(f);
}
return nothing();
}
Or, finally, you might throw an exception if you can't find anything:
Statement findFirstForLoop(loc project) {
decls = createAstsFromFiles(files, false);
visit(decls) {
case f:\for(_,_,_,_) : return f;
}
throw "couldn't find a for loop";
}
And a Bonus example collects all the for loops instead of finding the first:
list[Statement] getAllForLoops(loc project) {
decls = createAstsFromFiles(files, false);
result = [];
visit(decls) {
case f:\for(_,_,_,_) : result += [f];
}
return result;
}
Could also be written as a comprehension:
list[Statement] getAllForLoops(loc project) {
decls = createAstsFromFiles(files, false);
return [ f | /f:\for(_,_,_,_) := decls];
}
How do you create an empty list of tuples?
Just append it to the list, so that the tuple will be added instead of having the elements of the tuple extend the list.
ticketData.append(data)
will add data
to the list ticketData
Create a list of tuples dynamically in C#
"The method Add doesn't accept 2 arguments"
Correct, but you can pass a Tuple<int, int>
as a single argument to the list, since that's the type that the list contains.
"The code computes 2 integers in a for loop. I want to check in each loop whether the generated 2 integers already exist in myList and, if not, add it to myList"
Some code would help here, but I would suggest creating a Tuple<int, int>
from the two integers and then checking if that tuple already exists in the list or not (Tuple
overrides Equals
to compare the values of it's items with the corresponding items in the other Tuple
, so there's no extra work to do):
// We have two computed integers
int first = 5;
int second = 8;
// Add them as a Tuple to the list if it doesn't already exist
if (!myList.Contains((first, second))) myList.Add((first, second));
How to initialize variables that contains list of tuples in tensorflow?
sess = tf.Session() #NEW LINE
training_x = tf.Variable([[1, 1, 0], [1, 1, 1], [0, 1, 0], [-1, 1, 0], [-1, 0, 0], [-1, 0, 1],[0, 0, 1], [1, 1, 0], [1, 0, 0], [-1, 0, 0], [1, 0, 1], [0, 1, 1], [0, 0, 0], [-1, 1, 1]])
training_y = tf.Variable([[0], [0], [1], [1], [1], [0], [1],[0], [1], [1], [1], [1], [1], [0]])
init_op = tf.initialize_variables([training_x, training_y, test_x, test_y]) #NEW LINE
sess.run(init_op) #NEW LINE
model.fit(training_x, training_y, epochs=1000, steps_per_epoch=10)
# model.save_weights('demo_model.h5')
# model.load_weights('demo_model.h5')
text_x = tf.Variable([[1, 0, 0]])
test_y = model.predict(text_x, verbose=0, steps=1)
print(test_y)
Hopefully that gets your through your "uninitialized variables" issue.
Basically, the issue you're running into is that TF is a wrapper around C++. So, to handle some optimization stuff, they require you to 1) define all the variables, 2) initialize them BEFORE doing any operations. Hence, you faced the issue of
model.fit(training_x, training_y, epochs=1000, steps_per_epoch=10)
giving you the "uninitialized variables" error.
Hope this helps!
C# How to create and initialize a static array of ValueTuples?
You can't use the "cleaner" var
(implicit, but still strongly typed) type but you can initialize a tuple as the commenters have suggested. The "cleanest" you can get away with is this, which uses type inference on the array:
(int Index, string Name)[] tupleList = {
(1, "cow"),
(5, "chickens"),
(1, "airplane")
};
That, at least, allows you to avoid specifying the type twice, which is one reason people use var
.
The language does not support the use of var
when declaring member variables. This is true of both static and instance fields.
There's a historic reason for this. That's not to say it couldn't change if you propose a change and it's vetted by the community.
conversion of list of list of tuples to dict not working as expected
You can try nested slicing:
a = [[(1.0, 2481), (0.125, 5)],
[(1.0, 2481), (0.10526315789473684, 1), (0.0, 5), (0.0, 4), (0.0, 3), (0.0, 2)],
[(1.0, 2481), (0.11764705882352941, 2), (0.0, 5), (0.0, 4), (0.0, 3), (0.0, 1)],
[(1.0, 2481), (0.13333333333333333, 3), (0.0, 5), (0.0, 4), (0.0, 2), (0.0, 1)],
[(1.0, 2481), (0.1, 4), (0.0, 5), (0.0, 3), (0.0, 2), (0.0, 1)]]
b = [a[0][0]] + [i[1] for i in a]
print(b)
Output:
[(1.0, 2481),
(0.125, 5),
(0.10526315789473684, 1),
(0.11764705882352941, 2),
(0.13333333333333333, 3),
(0.1, 4)]
Initializing std::tuple from initializer list
Initializer lists aren't relevant for tuples.
I think that you're confusing two different uses of curly braces in C++0x.
initializer_list<T>
is a homogeneous collection (all members must be of the same type, so not relevant forstd::tuple
)- Uniform initialization is where curly brackets are used in order to construct all kinds of objects; arrays, PODs and classes with constructors. Which also has the benefit of solving the most vexing parse)
Here's a simplified version:
std::tuple<int, char> t = { 1, '1' };
// error: converting to 'std::tuple<int, char>' from initializer list would use
// explicit constructor 'std::tuple<_T1, _T2>::tuple(_U1&&, _U2&&)
// [with _U1 = int, _U2 = char, _T1 = int, _T2 = char]'
std::tuple<int, char> t { 1, '1' }; // note no assignment
// OK, but not an initializer list, uniform initialization
The error message says is that you're trying to implicitly call the constructor but it's an explicit constructor so you can't.
Basically what you're trying to do is something like this:
struct A {
explicit A(int) {}
};
A a0 = 3;
// Error: conversion from 'int' to non-scalar type 'A' requested
A a1 = {3};
// Error: converting to 'const A' from initializer list would use
// explicit constructor 'A::A(int)'
A a2(3); // OK C++98 style
A a3{3}; // OK C++0x Uniform initialization
How to split a list of tuples based on the minimum value in each tuple?
List comprehension with simple check could give you desired output:
x = [(1,2,3), (2,3,1), (0,10,100), (4,0,5), (2,1,3), (3.3,9,1.2), (4.5,2,0), (2,4,10), (100, 10, 30)]
x1 = [i for i in x if i[0] == min(i)]
x2 = [i for i in x if i[1] == min(i)]
x3 = [i for i in x if i[2] == min(i)]
Related Topics
Differencebetween a Property and a Variable
In C# Check That Filename Is *Possibly* Valid (Not That It Exists)
How to Get and Set the Window Position of Another Application in C#
Why Does Enumerable.All Return True for an Empty Sequence
Routing: the Current Request for Action [...] Is Ambiguous Between the Following Action Methods
How to Disable a Tab Inside a Tabcontrol
Get Os Version/Friendly Name in C#
An Attempt Was Made to Access a Socket in a Way Forbidden by Its Access Permissions
Zoom and Translate an Image from the Mouse Location
The Provided Uri Scheme 'Https' Is Invalid; Expected 'Http'. Parameter Name: Via
Filter/Search Using Multiple Fields - ASP.NET MVC
How to Flatten Nested Objects with Linq Expression
Export Datatable to Excel File
Retrieve System Uptime Using C#