I am learning C# and have been taking a lot of online courses.
I am looking for a simpler/neater way to enumerate a list within a list.
In python we can do something like this in just one line:
newListofList=[[n,i] for n,i in enumerate([List1,List2,List3])]
Does it have to involve lambda and Linq in C#? if so, what would be the solution? I tried it with Dictionary in C# but my gut tells me this is not a perfect solution.
List<List<string>> familyListss = new List<List<string>>();
familyListss.Add(new List<string> { "Mary", "Mary_sister", "Mary_father", "Mary_mother", "Mary_brother" });
familyListss.Add(new List<string> { "Peter", "Peter_sister", "Peter_father", "Peter_mother", "Peter_brother" });
familyListss.Add(new List<string> { "John", "John_sister", "John_father", "John_mother", "John_brother" });
Dictionary<int, List<string>> familyData = new Dictionary<int, List<string>>();
for (int i = 0; i < familyListss.Count; i++)
{
familyData.Add(i, familyListss[i]);
}
Just a constructor will be enough:
List<List<string>> familyListss = new List<List<string>>() {
new List<string> { "Mary", "Mary_sister", "Mary_father", "Mary_mother", "Mary_brother" },
new List<string> { "Peter", "Peter_sister", "Peter_father", "Peter_mother", "Peter_brother" },
new List<string> { "John", "John_sister", "John_father", "John_mother", "John_brother" }
};
If you want to mimic enumerate you can use Linq, Select((value, index) => your lambda here):
using System.Linq;
...
var list = new List<string>() {
"a", "b", "c", "d"};
var result = list
.Select((value, index) => $"item[{index}] = {value}");
Console.Write(string.Join(Environment.NewLine, result));
Outcome:
item[0] = a
item[1] = b
item[2] = c
item[3] = d
Are you taking about something like this?
int i = 0;
familyListss.ForEach(f => { familyData.Add(i, f);i++; });
This is refactored from
int i = 0;
foreach (var f in familyListss)
{
familyData.Add(i, f);
i++;
}
With a small extension method, you can build in an index to foreach to make it one line. Extension methods are worth exploring, and can take annoying, repeated tasks out of your way.
Also see this question:
C# Convert List<string> to Dictionary<string, string>
Related
This code coverts an Array Buffer to a String and vice versa
function ab2str(buf) {
return String.fromCharCode.apply(null, new Uint16Array(buf));
}
function str2ab(str) {
var buf = new ArrayBuffer(str.length*2); // 2 bytes for each char
var bufView = new Uint16Array(buf);
for (var i=0, strLen=str.length; i < strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
}
I think Python bytearray() can do the job.
u can refer this page for more info: https://www.programiz.com/python-programming/methods/built-in/bytearray
Am trying to solve this problem statement.
It basically wants you to change the duplicates in the given vector to a unique form:
Ex: ["name","name","name1"] -> ["name","name2","name1"]... you get the idea
So I thought of using std::map to create a dictionary (I could also have used unordered_map here)
This is how I used the map:
std::vector<std::string> getFolderNames(std::vector<std::string>& names) {
std::vector<std::string> vec_list_of_folders;
std::map<std::string, int> map_of_names;
for (const auto& name : names) {
if (map_of_names.find(std::string(name)) == map_of_names.end()) {
map_of_names.insert(std::make_pair(name, 1));
}
else {
map_of_names[name] += 1;
}
}
puts("");
return vec_list_of_folders;
}
The function is still in debug mode (which explains why half the things in it are left uncoded)
I think the important part is:
for (const auto& name : names) {
if (map_of_names.find(std::string(name)) == map_of_names.end()) {
map_of_names.insert(std::make_pair(name, 1));
}
else {
map_of_names[name] += 1;
}
}
I wanted to know if there is an easy way to do this. Something like the following code in python:
file_names = ["file1", "file2", "file3", "file1"]
print(*file_names)
example_dict = dict()
for file_name in file_names:
example_dict[file_name] = example_dict.get(file_name, 0) + 1 # this is the function I'm searching an equivalent for
print(example_dict)
How do I go about this?
Your important part code is equivalent to:
for (const auto& name : names) {
map_of_names[name] += 1;
}
If name is not found, then the value type is default-constructed, and default-constructed int is 0.
You could do something similar in Python, using defaultdict:
import collections
file_names = ["file1", "file2", "file3", "file1"]
print(*file_names)
example_dict = collections.defaultdict(int)
for file_name in file_names:
example_dict[file_name] += 1
print(example_dict)
Since map is sorted one way to do it could be to check if a name is the same as its neigbour.
if (!names.empty()) {
for (auto it = std::next(names.begin()); it != names.end(); ++it) {
if (std::prev(it)->first == it->first) {
// handle this
}
}
}
I'm quite new with Rust, and my first 'serious' project has involved writing a Python wrapper for a small Rust library using PyO3. This has mostly been quite painless, but I'm struggling to work out how to expose lazy iterators over Rust Vecs to Python code.
So far, I have been collecting the values produced by the iterator and returning a list, which obviously isn't the best solution. Here's some code which illustrates my problem:
use pyo3::prelude::*;
// The Rust Iterator, from the library I'm wrapping.
pub struct RustIterator<'a> {
position: usize,
view: &'a Vec<isize>
}
impl<'a> Iterator for RustIterator<'a> {
type Item = &'a isize;
fn next(&mut self) -> Option<Self::Item> {
let result = self.view.get(self.position);
if let Some(_) = result { self.position += 1 };
result
}
}
// The Rust struct, from the library I'm wrapping.
struct RustStruct {
v: Vec<isize>
}
impl RustStruct {
fn iter(&self) -> RustIterator {
RustIterator{ position: 0, view: &self.v }
}
}
// The Python wrapper class, which exposes the
// functions of RustStruct in a Python-friendly way.
#[pyclass]
struct PyClass {
rust_struct: RustStruct,
}
#[pymethods]
impl PyClass {
#[new]
fn new(v: Vec<isize>) -> Self {
let rust_struct = RustStruct { v };
Self{ rust_struct }
}
// This is what I'm doing so far, which works
// but doesn't iterate lazily.
fn iter(&self) -> Vec<isize> {
let mut output_v = Vec::new();
for item in self.rust_struct.iter() {
output_v.push(*item);
}
output_v
}
}
I've tried to wrap the RustIterator class with a Python wrapper, but I can't use PyO3's #[pyclass] proc. macro with lifetime parameters. I looked into pyo3::types::PyIterator but this looks like a way to access a Python iterator from Rust rather than the other way around.
How can I access a lazy iterator over RustStruct.v in Python? It's safe to assume that the type contained in the Vec always derives Copy and Clone, and answers which require some code on the Python end are okay (but less ideal).
You can make your RustIterator a pyclass and then implement the proper trait (PyIterProtocol) using the rust iter itself.
Not tested, but something like:
#[pyclass]
pub struct RustIterator<'a> {
position: usize,
view: &'a Vec<isize>
}
impl<'a> Iterator for RustIterator<'a> {
type Item = &'a isize;
fn next(&mut self) -> Option<Self::Item> {
let result = self.view.get(self.position);
if let Some(_) = result { self.position += 1 };
result
}
}
#[pyproto]
impl PyIterProtocol for Iter {
fn __next__(mut slf: PyRefMut<Self>) -> IterNextOutput<usize, &'static str> {
match self.next() {
Some(value) => IterNextOutput::Yield(value),
None => IterNextOutput::Return("Ended")
}
}
}
I have multiple Hazelcast sets for which I want to find the Intersection, however I want to avoid pulling any data on the client side. My current approach is exactly that with this code. It finds intersection between the 1st set and the list of the rest of set so that set1 is now the intersection of all.
for i in range(1, len(sets)):
cur = sets[i]
set1.retain_all(cur.get_all())
Hazelcast's retain_all doesn't work with 2 set entities, only with a set and a collection which is not what I am looking for. For example, it can be done with Redis with this code, so I want its Hazelcast equivalent.
set_result = "set_result"
redisClient.sinterstore(set_result, *list(sets))
Any help would be appreciated!
Since Hazelcast's ISet is a Set which is a Collection the following code should work:
set1.retainAll(cur);
But, it doesn't seem like you'd like set1 to be modified but would rather store the result in a different set much like redis' sinterstore function.
The following is an example of an alternative implementation:
public class RetainAllExample {
public static void main(String[] args) {
HazelcastInstance h1 = Hazelcast.newHazelcastInstance();
HazelcastInstance h2 = Hazelcast.newHazelcastInstance();
Set<String> set1 = h1.getSet("set1");
Set<String> set2 = h1.getSet("set2");
set1.add("a");
set1.add("b");
set1.add("c");
set1.add("d");
set2.add("c");
set2.add("d");
set2.add("e");
String resultName = "result";
String[] setNames = new String[] { "set1", "set2"};
RetainAll retainAll = new RetainAll(resultName, setNames;
IExecutorService exec = h1.getExecutorService("HZ-Executor-1");
Future<Boolean> task = exec.submit(retainAll);
try {
if(task.get(1_000, TimeUnit.MILLISECONDS)) {
Set<String> result = h1.getSet(resultName);
result.forEach(str -> System.out.println(str + ", "));
}
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
System.exit(0);
}
static class RetainAll implements Callable<Boolean>, HazelcastInstanceAware, Serializable {
private HazelcastInstance hazelcastInstance;
private String resultSetName;
private String[] setNames;
public RetainAll(String resultSetName, String[] setNames) {
this.resultSetName = resultSetName;
this.setNames = setNames;
}
#Override
public Boolean call() {
try {
Set[] sets = new Set[setNames.length];
IntStream.range(0, setNames.length).forEach(i -> sets[i] = hazelcastInstance.getSet(setNames[i]));
ISet resultSet = hazelcastInstance.getSet(resultSetName);
resultSet.addAll(sets[0]);
IntStream.range(1, sets.length).forEach(i -> resultSet.retainAll(sets[i]));
}
catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
#Override
public void setHazelcastInstance(HazelcastInstance hazelcastInstance) {
this.hazelcastInstance = hazelcastInstance;
}
}
}
I am creating a simple GUI program to manage priorities.
I am having troubles with deleting selected items from the listbox, as well as from the list at the same time.
For instance, in C#, I would create a following method:
void Remove()
{
Priority priority = new Priority();
try { priority = FindPriority(listView1.SelectedItems[0].Text); }
catch { return; }
if (listView1.SelectedItems.Count > 0)
{
try
{
foreach (ListViewItem eachItem in listView1.SelectedItems)
{
priorities.RemoveAll(x => x.Subject == eachItem.Text);
listView1.Items[listView1.Items.Count - 1].Selected = true;
listView1.Items.Remove(eachItem);
}
}
catch { }
}
else
{
MessageBox.Show("You have not selected any priorities!", "Notification", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
How can I do this in Python?
I'm using Python 3.5.