How can I print out a list? - list

I have this dictionary:
ANIMALS = {
"a": "ape",
"k": "kangaroo",
"#": "cat",
"h": "horse",
"l": "lamb"
}
and this list:
pelto = [
[" ", "a", " ", " ", "l"],
[" ", "k", "#", "k", " "],
["h", " ", "a", "k", " "]
]
I need to go through the list and find the indexes of every string in there.
After that I'd need to print everything out to something like this:
In (1, 0) there's an ape
In (4, 0) there's a lamb
In (1, 1) there's a kangaroo
In (2, 1) there's a cat
In (3, 1) there's a kangaroo
In (0, 2) there's a horse
In (2, 2) there's an ape
In (3, 2) there's a kangaroo
Any ideas?

well the easy way to do this, is using the .index() in python (I am assuming this is python because of the dictionary), so the code that does that printing is this:
ANIMALS = {
"a": "ape",
"k": "kangaroo",
"#": "cat",
"h": "horse",
"l": "lamb"
}
pelto = [
[" ", "a", " ", " ", "l"],
[" ", "k", "#", "k", " "],
["h", " ", "a", "k", " "]
]
for list in pelto:
for item in list:
if item is not " ":
print(f'In ({list.index(item)}, {pelto.index(list)}) there\'s an {ANIMALS[item]}')
This is the result that you are waiting for:
In (1, 0) there's an ape
In (4, 0) there's an lamb
In (1, 1) there's an kangaroo
In (2, 1) there's an cat
In (1, 1) there's an kangaroo
In (0, 2) there's an horse
In (2, 2) there's an ape
In (3, 2) there's an kangaroo

Related

Group list of tuples and sum the integers

I have the following list:
List(List(("hello", "goodbye", 12), ("hello", "goodbye", 15)), List(("hello", "test", 18), ("hello", "test", 20)), List(("something", "different", 30), ("something", "different", 18)))
I would like to get the following result:
List(("hello", "goodbye", 27), ("hello", "test", 38), ("something", "different", 48))
I've tried to use .map and .groupBy, but I can't seem to find a way to get it working.
This appears to get what you're after as long as the order of result elements is unimportant.
val data =
List(List(("hello", "goodbye", 12), ("hello", "goodbye", 15)), List(("hello", "test", 18), ("hello", "test", 20)), List(("something", "different", 30), ("something", "different", 18)))
data.flatten
.groupMapReduce(tup => (tup._1,tup._2))(_._3)(_+_)
.map{case ((k1,k2),v) => (k1,k2,v)}
.toList
//res0: List[(String, String, Int)] =
// List((hello,test,38), (something,different,48), (hello,goodbye,27))
Notice that I flatten away all the inner sub-Lists and focus only on the String elements in the tuples. It's not completely clear if that's what you intend.
You can:
Flatten those lists into a single list
Group by the first two elements of each list
Reduce on the third element of each list in each group
val list = List(
List(("hello", "goodbye", 12), ("hello", "goodbye", 15)),
List(("hello", "test", 18), ("hello", "test", 20)),
List(("something", "different", 30), ("something", "different", 18))
)
val result = list.flatten.groupBy { case (s1, s2, _) => (s1, s2) }.values.map(_.reduce((s1, s2) => (s1._1, s1._2, s1._3 + s2._3)))
// List((hello,test,38), (hello,goodbye,27), (something,different,48))
If inner list can have different "keys" - you can flatten your list of lists with flatMap(identity) or flatten then group the result using first two elements of the tuples and reduce the groupping with sum:
val collection = ...
collection
.flatten
.groupMapReduce(t => (t._1, t._2))(identity)((l,r) => (l._1, l._2, l._3+r._3))
.values
.toList

How to separate similar tuples based on some similar attribute?

I have a tuple list which looks like this:
val days= List(("Sunday", 1), ("Monday", 2), ("Tuesday", 1),
("Wednesday", 2), ("Thursday", 3), ("Friday", 2),
("Saturday", 3))
I want the final result to look like this:
"data": [
[
"Sunday, 1",
"Tuesday, 1"
],
[
"Monday, 2",
"Friday, 2"
"Wednesday,2"
],
[
"Thursday, 3",
"Saturday,3"
]
]
You can group and then map values:
days.groupBy(_._2)
.mapValues(_.map { case (name, nr) => s"$name, $nr" } )
.valuesIterator.toList
The result is:
List(List(Monday, 2, Wednesday, 2, Friday, 2), List(Sunday, 1, Tuesday, 1), List(Thursday, 3, Saturday, 3))
P.S.: As Luis Miguel Mejía Suárez suggests, using groupMap (from scala 2.13) can make this a bit more concise and readable:
days.groupMap(_._2) { case (name, nr) => s"$name, $nr" }
.valuesIterator.toList

Concatenate lists with Python

I would like to concatenate two lists:
list_a = ["hello", "world"]
list_b = ["a", "b", "c", "d"]
and get something like this as output:
list_c = ["hello a", "hello b", "hello c", "hello d", "world a", "world b", "world c", "world d"]
The second list is basically going from a to z and create combinations with the list_a.
from functools import reduce
list_a = ["hello", "world"]
list_b = ["a", "b", "c", "d"]
def cross_join_lists(word):
return [f'{word} {letter}' for letter in list_b]
def concat_lists(final_list, a_list):
return final_list + a_list
joined_lists = list(map(cross_join_lists, list_a))
list_c = reduce(concat_lists, joined_lists)
print(list_c)
You can use a list comprehension:
new_list = [f"{i} {j}" for i in list_a for j in list_b]
# output: ['hello a', 'hello b', 'hello c', 'hello d', 'world a', 'world b',
'world c', 'world d']

How to count items' occurence in a List

I am new to Dart. Currently I have a List of duplicate items, and I would like to count the occurence of them and store it in a Map.
var elements = ["a", "b", "c", "d", "e", "a", "b", "c", "f", "g", "h", "h", "h", "e", "a"];
I want to have a result like:
{
"a": 3,
"b": 2,
"c": 2,
"d": 2,
"e": 2,
"f": 1,
"g": 1,
"h": 3
}
I did some research and found a JavaScript solution, but I don't know how to translate it to Dart.
var counts = {};
your_array.forEach(function(x) { counts[x] = (counts[x] || 0)+1; });
Play around with this:
var elements = ["a", "b", "c", "d", "e", "a", "b", "c", "f", "g", "h", "h", "h", "e"];
var map = Map();
elements.forEach((element) {
if(!map.containsKey(element)) {
map[element] = 1;
} else {
map[element] += 1;
}
});
print(map);
What this does is:
loops through list elements
if your map does not have list element set as a key, then creates that element with a value of 1
else, if element already exists, then adds 1 to the existing key value
Or if you like syntactic sugar and one liners try this one:
var elements = ["a", "b", "c", "d", "e", "a", "b", "c", "f", "g", "h", "h", "h", "e"];
var map = Map();
elements.forEach((x) => map[x] = !map.containsKey(x) ? (1) : (map[x] + 1));
print(map);
There are many ways to achieve this in all programming languages!
The shorter way to count items' occurrence in a List
List of items. Count items equal 1.
List<int> lst = [0,1,1,1,0,8,8,9,1,0];
int res = lst.map((element) => element == 1 ? 1 : 0).reduce((value, element) => value + element);
List of objects. Count objects, which property age equals 1.
class Person {
int age;
Person(this.age);
}
List<Person> lst2 = [Person(1), Person(0), Person(1), Person(0)];
int res2 = lst2.map((element) => element.age == 1 ? 1 : 0).reduce((value, element) => value + element);
Use fold with a map:
final elements = ["a", "b", "c", "d", "e", "a", "b", "c", "f", "g", "h", "h", "h", "e", "a"];
var counts = elements.fold<Map<String, int>>({}, (map, element) {
map[element] = (map[element] ?? 0) + 1;
return map;
});
print(counts);
Out: {a: 3, b: 2, c: 2, d: 1, e: 2, f: 1, g: 1, h: 3}

wxpython: 'Example' object has no attribute 'OnClick'

I am making a GUI of the periodic table of elements with wxpython, I have added all the buttons. So now what I want is when the user selects multiple buttons it should give me output same as the labeled on the button. Trying to run this code but getting the error. Don't know what's wrong, I am doing here.
import wx
class Example(wx.Frame):
def __init__(self, parent, title):
super(Example, self).__init__(parent, title=title, size=(1000, 800))
self.InitUI()
self.Centre()
self.Show()
def InitUI(self):
p = wx.Panel(self)
gs = wx.GridSizer(11, 18, 5, 1)
A = ["H", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", "He", "Li", "Be", " ",
" ",
" ", " ", " ", " ", " ", " ", " ", " ", "B", "C", "N", "O", "F", "Ne", "Na", "Mg", " ", " ", " ", " ", " ",
" ",
" ", " ", " ", " ", "Al", "Si", "P", "S", "Cl", "Ar", "K", "Ca", "Sc", "Ti", "V", "Cr", "Mn", "Fe", "Co",
"Ni",
"Cu", "Zn", "Ga", "Ge", "As", "Se", "Br", "Kr", "Rb", "Sr", "Y", "Zr", "Nb", "Mo", "Tc", "Ru", "Rh", "Pd",
"Ag",
"Cd", "In", "Sn", "Sb", "Te", "I", "Xe", "Cs", "Ba", "", "Hf", "Ta", "W", "Re", "Os", "Ir", "Pt", "Au",
"Hg", "Tl",
"Pb", "Bi", "Po", "At", "Rn", "Fr", "Ra", "", "Rf", "Db", "Sg", "Bh", "Hs", "Mt", "Ds", "Rg", "Cn", "Nh",
"Fl",
"Mc", "Lv", "Ts", "Og",
" ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ",
"La",
"Ce", "Pr", "Nd", "Pm", "Sm", "Eu", "Gd", "Tb", "Dy", "Ho", "Er", "Tm", "Yb", "Lu", " ", " ", " ", "Ac",
"Th",
"Pa", "U", "Np", "Pu", "Am", "Cm", "Bk", "Cf", "Es", "Fm", "Md", "No", "Lr", " ", " ", " ", " ", " ", " ",
" ",
" ", " ", "Go", " ", " ", " ", " ", " ", " ", " ", " "]
for i in A:
btn = str(i)
a = wx.Button(self, 10, "str(i)", (20, 20)) # buttons are added
a.myname = "str(i)"
self.Bind(wx.EVT_BUTTON, self.OnClick, a)
print(i)
def OnClick(self, event): # When the button is clicked
name = event.GetEventObject().myname
p.SetSizer(gs)
app = wx.App()
Example(None, title='Grid demo')
app.MainLoop()
Well, it seems that the third argument in self.Bind(wx.EVT_BUTTON, self.OnClick, a) is useless, try self.Bind(wx.EVT_BUTTON, self.OnClick)
(comparing with code generated thanks to wxformbuilder)
It's all a bit tight given the number of buttons and you must declare the buttons as part of the panel, not hope that the sizer will do the work for you.
There are few changes but they are important.
Code now includes elements{dictionary} for element display (I'm missing a few of the rarer elements like Oganesson but hey if you can't eat it, smoke it, make a purchase with it or use it to scale a mountain, who cares?)
import wx
class Example(wx.Frame):
def __init__(self, parent, title):
super(Example, self).__init__(parent, title = title,size = (2000,1000))
self.InitUI()
self.Layout()
self.Centre()
self.Show()
def InitUI(self):
self.elements = {'Ru': 'Ruthenium', 'Re': 'Rhenium', 'Rf': 'Rutherfordium', 'Rg': 'Roentgenium', 'Ra': 'Radium', 'Rb': 'Rubidium', 'Rn': 'Radon', 'Rh': 'Rhodium', 'Be': 'Beryllium', 'Ba': 'Barium', 'Bh': 'Bohrium', 'Bi': 'Bismuth', 'Bk': 'Berkelium', 'Br': 'Bromine', 'H': 'Hydrogen', 'P': 'Phosphorus', 'Os': 'Osmium', 'Es': 'Einsteinium', 'Hg': 'Mercury', 'Ge': 'Germanium', 'Gd': 'Gadolinium', 'Ga': 'Gallium', 'Pr': 'Praseodymium', 'Pt': 'Platinum', 'Pu': 'Plutonium', 'C': 'Carbon', 'Pb': 'Lead', 'Pa': 'Protactinium', 'Pd': 'Palladium', 'Cd': 'Cadmium', 'Po': 'Polonium', 'Pm': 'Promethium', 'Hs': 'Hassium', 'Uup': 'Ununpentium', 'Uus': 'Ununseptium', 'Uuo': 'Ununoctium', 'Ho': 'Holmium', 'Hf': 'Hafnium', 'K': 'Potassium', 'He': 'Helium', 'Md': 'Mendelevium', 'Mg': 'Magnesium', 'Mo': 'Molybdenum', 'Mn': 'Manganese', 'O': 'Oxygen', 'Mt': 'Meitnerium', 'S': 'Sulfur', 'W': 'Tungsten', 'Zn': 'Zinc', 'Eu': 'Europium', 'Zr': 'Zirconium', 'Er': 'Erbium', 'Ni': 'Nickel', 'No': 'Nobelium', 'Na': 'Sodium', 'Nb': 'Niobium', 'Nd': 'Neodymium', 'Ne': 'Neon', 'Np': 'Neptunium', 'Fr': 'Francium', 'Fe': 'Iron', 'Fl': 'Flerovium', 'Fm': 'Fermium', 'B': 'Boron', 'F': 'Fluorine', 'Sr': 'Strontium', 'N': 'Nitrogen', 'Kr': 'Krypton', 'Si': 'Silicon', 'Sn': 'Tin', 'Sm': 'Samarium', 'V': 'Vanadium', 'Sc': 'Scandium', 'Sb': 'Antimony', 'Sg': 'Seaborgium', 'Se': 'Selenium', 'Co': 'Cobalt', 'Cn': 'Copernicium', 'Cm': 'Curium', 'Cl': 'Chlorine', 'Ca': 'Calcium', 'Cf': 'Californium', 'Ce': 'Cerium', 'Xe': 'Xenon', 'Lu': 'Lutetium', 'Cs': 'Caesium', 'Cr': 'Chromium', 'Cu': 'Copper', 'La': 'Lanthanum', 'Li': 'Lithium', 'Lv': 'Livermorium', 'Tl': 'Thallium', 'Tm': 'Thulium', 'Lr': 'Lawrencium', 'Th': 'Thorium', 'Ti': 'Titanium', 'Te': 'Tellurium', 'Tb': 'Terbium', 'Tc': 'Technetium', 'Ta': 'Tantalum', 'Yb': 'Ytterbium', 'Db': 'Dubnium', 'Dy': 'Dysprosium', 'Ds': 'Darmstadtium', 'I': 'Iodine', 'U': 'Uranium', 'Y': 'Yttrium', 'Ac': 'Actinium', 'Ag': 'Silver', 'Uut': 'Ununtrium', 'Ir': 'Iridium', 'Am': 'Americium', 'Al': 'Aluminium', 'As': 'Arsenic', 'Ar': 'Argon', 'Au': 'Gold', 'At': 'Astatine', 'In': 'Indium'}
p = wx.Panel(self)
gs = wx.GridSizer(11, 18, 5, 5)
A = [ "H"," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," ", "He", "Li", "Be"," "," "," "," "," "," "," "," "," "," ", "B" , "C", "N", "O", "F" , "Ne", "Na", "Mg"," "," "," "," "," "," "," "," "," "," ", "Al", "Si", "P", "S", "Cl", "Ar", "K", "Ca","Sc", "Ti", "V", "Cr", "Mn", "Fe", "Co", "Ni", "Cu", "Zn", "Ga", "Ge", "As", "Se", "Br", "Kr", "Rb", "Sr", "Y", "Zr", "Nb", "Mo", "Tc", "Ru","Rh", "Pd", "Ag", "Cd", "In", "Sn", "Sb", "Te", "I", "Xe", "Cs", "Ba", "" , "Hf", "Ta", "W", "Re", "Os", "Ir", "Pt", "Au", "Hg", "Tl", "Pb", "Bi", "Po", "At", "Rn", "Fr", "Ra", "", "Rf", "Db", "Sg", "Bh", "Hs","Mt", "Ds", "Rg", "Cn", "Nh", "Fl", "Mc", "Lv", "Ts", "Og"," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," ", " ", " "," ", " ", " ", "La", "Ce", "Pr", "Nd", "Pm", "Sm", "Eu", "Gd", "Tb", "Dy", "Ho", "Er", "Tm","Yb", "Lu"," ", " ", " ","Ac", "Th" , "Pa", "U", "Np", "Pu", "Am", "Cm", "Bk","Cf", "Es", "Fm", "Md" , "No", "Lr"," "," "," "," "," "," "," "," "," " ,"Go"," "," "," "," "," "," "," ","ZZ" ]
for i in A:
btn = wx.Button(p, -1, i, (10,20)) #buttons are added
btn.myname = i
gs.Add(btn,0,)
self.Bind(wx.EVT_BUTTON, self.OnClick, btn)
p.SetSizer(gs)
def OnClick(self, event): #When the button is clicked
name = event.GetEventObject().myname
try:
element = self.elements[name]
wx.MessageBox("You selected element "+element, "Selection",wx.ICON_INFORMATION | wx.OK)
except:
wx.MessageBox("You selected element "+name, "Selection",wx.ICON_INFORMATION | wx.OK)
app = wx.App()
Example(None, title = 'Grid demo')
app.MainLoop()
New version based on your other question Error with on click event in wxpython
import wx
class Example(wx.Frame):
def __init__(self, parent, title):
super(Example, self).__init__(parent, title = title,size = (1400,500))
self.InitUI()
self.Layout()
self.Centre()
self.Show()
def InitUI(self):
self.elements = {'Ru': 'Ruthenium', 'Re': 'Rhenium', 'Rf': 'Rutherfordium', 'Rg': 'Roentgenium', 'Ra': 'Radium', 'Rb': 'Rubidium', 'Rn': 'Radon', 'Rh': 'Rhodium', 'Be': 'Beryllium', 'Ba': 'Barium', 'Bh': 'Bohrium', 'Bi': 'Bismuth', 'Bk': 'Berkelium', 'Br': 'Bromine', 'H': 'Hydrogen', 'P': 'Phosphorus', 'Os': 'Osmium', 'Es': 'Einsteinium', 'Hg': 'Mercury', 'Ge': 'Germanium', 'Gd': 'Gadolinium', 'Ga': 'Gallium', 'Pr': 'Praseodymium', 'Pt': 'Platinum', 'Pu': 'Plutonium', 'C': 'Carbon', 'Pb': 'Lead', 'Pa': 'Protactinium', 'Pd': 'Palladium', 'Cd': 'Cadmium', 'Po': 'Polonium', 'Pm': 'Promethium', 'Hs': 'Hassium', 'Uup': 'Ununpentium', 'Uus': 'Ununseptium', 'Uuo': 'Ununoctium', 'Ho': 'Holmium', 'Hf': 'Hafnium', 'K': 'Potassium', 'He': 'Helium', 'Md': 'Mendelevium', 'Mg': 'Magnesium', 'Mo': 'Molybdenum', 'Mn': 'Manganese', 'O': 'Oxygen', 'Mt': 'Meitnerium', 'S': 'Sulfur', 'W': 'Tungsten', 'Zn': 'Zinc', 'Eu': 'Europium', 'Zr': 'Zirconium', 'Er': 'Erbium', 'Ni': 'Nickel', 'No': 'Nobelium', 'Na': 'Sodium', 'Nb': 'Niobium', 'Nd': 'Neodymium', 'Ne': 'Neon', 'Np': 'Neptunium', 'Fr': 'Francium', 'Fe': 'Iron', 'Fl': 'Flerovium', 'Fm': 'Fermium', 'B': 'Boron', 'F': 'Fluorine', 'Sr': 'Strontium', 'N': 'Nitrogen', 'Kr': 'Krypton', 'Si': 'Silicon', 'Sn': 'Tin', 'Sm': 'Samarium', 'V': 'Vanadium', 'Sc': 'Scandium', 'Sb': 'Antimony', 'Sg': 'Seaborgium', 'Se': 'Selenium', 'Co': 'Cobalt', 'Cn': 'Copernicium', 'Cm': 'Curium', 'Cl': 'Chlorine', 'Ca': 'Calcium', 'Cf': 'Californium', 'Ce': 'Cerium', 'Xe': 'Xenon', 'Lu': 'Lutetium', 'Cs': 'Caesium', 'Cr': 'Chromium', 'Cu': 'Copper', 'La': 'Lanthanum', 'Li': 'Lithium', 'Lv': 'Livermorium', 'Tl': 'Thallium', 'Tm': 'Thulium', 'Lr': 'Lawrencium', 'Th': 'Thorium', 'Ti': 'Titanium', 'Te': 'Tellurium', 'Tb': 'Terbium', 'Tc': 'Technetium', 'Ta': 'Tantalum', 'Yb': 'Ytterbium', 'Db': 'Dubnium', 'Dy': 'Dysprosium', 'Ds': 'Darmstadtium', 'I': 'Iodine', 'U': 'Uranium', 'Y': 'Yttrium', 'Ac': 'Actinium', 'Ag': 'Silver', 'Uut': 'Ununtrium', 'Ir': 'Iridium', 'Am': 'Americium', 'Al': 'Aluminium', 'As': 'Arsenic', 'Ar': 'Argon', 'Au': 'Gold', 'At': 'Astatine', 'In': 'Indium'}
p = wx.Panel(self)
hbox1= wx.BoxSizer(wx.VERTICAL)
self.t1= wx.TextCtrl (p,0,value="",size=(120,30),style=wx.TE_READONLY)
hbox1.Add(self.t1,proportion=0,flag=wx.CENTER)
gs = wx.GridSizer(11, 18, 5, 5)
A = [ "H"," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," ", "He", "Li", "Be"," "," "," "," "," "," "," "," "," "," ", "B" , "C", "N", "O", "F" , "Ne", "Na", "Mg"," "," "," "," "," "," "," "," "," "," ", "Al", "Si", "P", "S", "Cl", "Ar", "K", "Ca","Sc", "Ti", "V", "Cr", "Mn", "Fe", "Co", "Ni", "Cu", "Zn", "Ga", "Ge", "As", "Se", "Br", "Kr", "Rb", "Sr", "Y", "Zr", "Nb", "Mo", "Tc", "Ru","Rh", "Pd", "Ag", "Cd", "In", "Sn", "Sb", "Te", "I", "Xe", "Cs", "Ba", "" , "Hf", "Ta", "W", "Re", "Os", "Ir", "Pt", "Au", "Hg", "Tl", "Pb", "Bi", "Po", "At", "Rn", "Fr", "Ra", "", "Rf", "Db", "Sg", "Bh", "Hs","Mt", "Ds", "Rg", "Cn", "Nh", "Fl", "Mc", "Lv", "Ts", "Og"," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," ", " ", " "," ", " ", " ", "La", "Ce", "Pr", "Nd", "Pm", "Sm", "Eu", "Gd", "Tb", "Dy", "Ho", "Er", "Tm","Yb", "Lu"," ", " ", " ","Ac", "Th" , "Pa", "U", "Np", "Pu", "Am", "Cm", "Bk","Cf", "Es", "Fm", "Md" , "No", "Lr"," "," "," "," "," "," "," "," "," " ," "," "," "," "," "," "," "," "," "]
for element in A:
btn = wx.Button(p, -1, element, (10,20)) #buttons are added
btn.name = element
gs.Add(btn,0,)
self.Bind(wx.EVT_BUTTON, self.OnClick, btn)
hbox1.Add(gs,proportion=0)
p.SetSizer(hbox1)
def OnClick(self, event): #When the button is clicked
name = event.GetEventObject().name
try:
element = self.elements[name]
except:
element = name
self.t1.SetValue(element)
app = wx.App()
Example(None, title = 'Element Grid')
app.MainLoop()
This is now the third time that I have asked you to read how StackOverflow works, please read the tour pages. Ultimately, this is for your own good.