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']
Related
I have a slug ArrayField on a model.
How can I filter or get by the entire exact array only?
I'm currently doing something like this:
search = f'["a", "b", "c"]'
list = search[2:-2].split("', '")
dict = {}
for n, item in enumerate(list):
dict[f"slug__{n}"] = item
obj = queryset.filter(**dict)
However, this returns any object where the slug begins with "a", "b", and "c".
E.g.
["a", "b", "c"]
["a", "b", "c", "d"]
["a", "b", "c", "d", "e"]
["a", "b", "c", "123"]
How do I do a filter or get so that only the entire and exact slug match returns? I.e. obj only returns objects with a slug of ["a", "b", "c"]
To filter an ArrayField by an exact match you can just pass the list to match against to a filter
queryset = queryset.filter(slug=["a", "b", "c"])
I want to add data to list of dictionaries
a =[100, 200, 300]
b =['apple', 'orange', 'grapes']
c=[]
for val in a:
c.append({'price':val})
for val in b:
c.append({'fruit':val})
print(c)
result should be like this:
[
{'price':100, 'fruit':'apple'}, {'price':200, 'fruit':'orange'}, {'price':300, 'fruit':'grapes'}
You can work with list comprehension:
a = [100, 200, 300]
b = ['apple', 'orange', 'grapes']
c = [{'price': p, 'fruit': f} for p, f in zip(a, b)]
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}
I'm new in swift. I'm trying to add an Array to a specific key in my Dictionary.
I have the following code:
var myArray : Array<Links> = []
var myDict : Dictionary<String, AnyObject> = [:]
myDict["links"] = myArray as AnyObject? // I need help in this row, It does not work.
This is the Json structure I have in myDict and I'm trying to set:
id : "blabla"
links: [
0: {key1: "a", key2: "b", name: "c", link: "d"}
1: {key1: "e", key2: "f", name: "j", link: "h"}
]
Please, consider I already have all the rest working properly. My only problem is how to add my array in the dictionary as commented in the code above.
My JSON structure:
I hope I could make myself clear enough.
Thank you.
First of all don't cast types up and don't annotate types unless the compiler complains.
Second of all a JSON dictionary is [String:Any] in Swift 3.
Further the recommended syntax to create an empty collection object is
var myDict = Dictionary<String, Any>()
Assuming your array – actually a dictionary – is
let myArray = [
0: ["key1": "a", "key2": "b", "name": "c", "link": "d"],
1: ["key1": "e", "key2": "f", "name": "j", "link": "h"]
]
just assign it:
myDict["links"] = myArray
Even if there is a struct
struct Link {
var key1, key2, name, link : String
}
and the array dictionary is
let linkDictionary = [
0: Link(key1:"a", key2: "b", name: "c", link: "d"),
1: Link(key1:"e", key2: "f", name: "g", link: "h")]
you can assign it if the value type is Any
myDict["links"] = linkDictionary
Assuming, for a second, that links really was an array, it would be:
var dictionary: [String: Any] = [
"id": "blabla",
"links": [
["key1": "a", "key2": "b", "name": "c", "link": "d"],
["key1": "e", "key2": "f", "name": "j", "link": "h"]
]
]
// retrieve links, or initialize it if not found
var links = dictionary["links"] as? [[String: String]] ?? [[String: String]]()
// add your new link to local dictionary
links.append(["key1": "k", "key2": "l", "name": "m", "link": "n"])
// update original structure
dictionary["links"] = links
Personally, though, when I see a repeating dictionary structure like your links, this screams for a real model for these objects. For example:
struct Foo {
let id: String
var links: [Link]?
}
struct Link {
let key1: String
let key2: String
let name: String
let link: String
}
var foo = Foo(id: "blabla", links: [
Link(key1: "a", key2: "b", name: "c", link: "d"),
Link(key1: "e", key2: "f", name: "j", link: "h")
])
foo.links?.append(Link(key1: "k", key2: "l", name: "m", link: "n"))
Now, in this latter example, I assumed that links was really an array, not a dictionary, but that's not really my point here. My key observation is that code is more readable and robust if you use proper custom types rather than just arrays and dictionaries.
And if you need to send and receive these model objects to some web service, you then map this model object to and from JSON. But use custom types for your actual model.
If you want to make the above types easily converted to and from JSON, you can use one of the object mapping libraries out there, so you can do something yourself, e.g.:
protocol Jsonable {
var jsonObject: Any { get }
init?(jsonObject: Any)
}
extension Foo: Jsonable {
var jsonObject: Any {
return [
"id": id,
"links": links?.map { $0.jsonObject } ?? [Any]()
]
}
init?(jsonObject: Any) {
guard let dictionary = jsonObject as? [String: Any],
let id = dictionary["id"] as? String else { return nil }
var links: [Link]?
if let linksDictionary = dictionary["links"] as? [Any] {
links = linksDictionary.map { Link(jsonObject: $0)! }
}
self.init(id: id, links: links)
}
}
extension Link: Jsonable {
var jsonObject: Any { return [ "key1": key1, "key2": key2, "name": name, "link": link ] }
init?(jsonObject: Any) {
guard let dictionary = jsonObject as? [String: Any],
let key1 = dictionary["key1"] as? String,
let key2 = dictionary["key2"] as? String,
let name = dictionary["name"] as? String,
let link = dictionary["link"] as? String else {
return nil
}
self.init(key1: key1, key2: key2, name: name, link: link)
}
}
Then you can do stuff like:
let object = try JSONSerialization.jsonObject(with: data)
var foo = Foo(jsonObject: object)!
Or:
foo.links?.append(Link(key1: "j", key2: "k", name: "l", link: "m"))
let data = try! JSONSerialization.data(withJSONObject: foo.jsonObject)
This was the solution:
var arrLinks : Array<Dictionary<String, Any>> = []
for link in myArray {
var dict : Dictionary<String, Any> = [:]
dict["key1"] = link.name
dict["key2"] = link.ghostBefore
dict["key3"] = link.ghostAfter
arrLinks.append(dict)
}
myDict["links"] = arrLinks as AnyObject
I wrote a program that selects random words from lists to make a sentence. I want to write grammar rules for this. Right now I am working on plurals.
I want to add an s or es to the end of the selected word in 'nouns' if the word "those" is selected from list5.
import random
class Wrds(object):
verbs = [
"walk", "run"
]
pronouns = [
"I", "you"
]
help_verbs = [
"will", "might"
]
nouns = [
"boy", "girl"
]
list5 = [
"the", "that", "this", "a", "those"
]
punctuation = [
".", "?", "!"
]
def result(self):
a = random.choice(Wrds.verbs)
b = random.choice(Wrds.pronouns)
c = random.choice(Wrds.help_verbs)
d = random.choice(Wrds.nouns)
e = random.choice(Wrds.list5)
f = random.choice(Wrds.punctuation)
print "%s %s %s %s %s%s" % (b, c, a, e, d, f)
def ask():
a = raw_input("> ")
if a == "go":
w = Wrds()
return w.result()
elif a == "exit":
exit()
while True:
ask()
Before the print statement in the result method, add:
if e == 'those':
d += 's'