Use a dictionary for a variable number of variables
The Pythonic solution is to use collections.defaultdict:
from collections import defaultdict
d = defaultdict(list)
for item in original_list:
d[item['amenity']].append(item)
print(d['Pool'])
[{'amenity': 'Pool', 'amount': 300, 'id': 5, 'percentage': 10, 'version': 2},
{'amenity': 'Pool', 'amount': 200, 'id': 2, 'percentage': 10, 'version': 1}]
print(d['Parking'])
[{'amenity': 'Parking', 'amount': 120, 'version': 1, 'percentage': 4, 'id': 1}]
My intention is that when I order them in that way I can get the object with the greatest version per list using a lambda equation.
You can use a dictionary comprehension with max for this task:
res = {k: max(v, key=lambda x: x['version']) for k, v in d.items()}
{'Parking': {'amenity': 'Parking',
'amount': 120,
'id': 1,
'percentage': 4,
'version': 1},
'Pool': {'amenity': 'Pool',
'amount': 300,
'id': 5,
'percentage': 10,
'version': 2}}
Answer from jpp on Stack Overflowpython - Split list into sub-lists based on attribute value - Stack Overflow
qgis - I am looking for a Python method to Split the list of attributes in a layer - Geographic Information Systems Stack Exchange
python - Splitting a list of objects into n lists while keeping all attributes - Stack Overflow
python - How to slice a list of objects in association of the object attributes - Stack Overflow
How do I fix 'NoneType object has no attribute'?
What is Python AttributeError and what causes it?
How do I prevent AttributeError from None values?
Although it is not a one-liner, by using a list, we make it more elegant:
spades, diamonds, clubs, hearts = collcard = [[] for _ in range(4)]
for c in cards:
collcard[c.suit.value].append(c)
Here we thus initialize a list with four empty sublists, then we append the card c to the list with index c.suit.value.
We use iterable unpacking to assign the first element to spades, the second to diamonds, etc.
The advantage is that we avoid sorting (which works in O(n log n)). So this algorithm has time complexity O(n) (given the amortized cost of list appending is O(1)).
Although oneliners are usually elegant, one should not put to much effort in writing these, since oneliners can be harder to understand, or have significant impact with respect to performance.
When iterated upon, itertools.groupby yields tuple objects: the key, and an iterable of the grouped values (allowing lazy evaluation of the data).
You just converted the tuple to a list, which isn't very useful.
Instead, you need to drop the key (for instance by unpacking it to _, pythonic way of telling that you're not using it) and force iteration on the values:
[list(g) for _,g in itertools.groupby(cards, lambda x: x.suit.value)]
now if you want to group and sort, it's not very efficient to pass sorted(cards) to groupby just for the pleasure to create a one-liner (one-liners are nice, but I prefer fast programs). Your approach works, or you can also use collections.defaultdict, and even name the dict with the proper color using an indirection, for instance like this:
import collections
cards = collections.defaultdict(list)
colors = ["spades","diamonds","clubs","hearts"]
for c in cards:
cards[colors[c.suit.value]].append(c)
Perhaps something like the following?
layer = qgis.utils.iface.activeLayer()
for feature in layer.getFeatures():
attrs = feature.attributes()
for i, j in list(enumerate(attrs)):
print "value" + str(i + 1) + " = " + str(j)
To print the field value you need to provide the field name or index:
Field Name:
for feature in LYR.getFeatures():
print feature['myFieldName']
Field Index (first field starts at zero):
for feature in LYR.getFeatures():
print feature[1] # this is the second field in the table
It's not very clear what you're trying to do, but this code will take the first five fixtures, and return a list of tuples, each of which contains a home and an away value of the respective object:
result = [(i.home, i.away) for i in fixtures[:5]]
This will separate the two into two lists:
homes = [i.home for i in fixtures[:5]]
aways = [i.away for i in fixtures[:5]]
Or on one line:
homes, aways = [i.home for i in fixtures[:5]], [i.away for i in fixtures[:5]]
Not quite the answer you were after, but (assuming [(home1, away1), (home2, away2), ...]) this is about as simple as you'll get.
homes = [h for h,a in fixtures]
aways = [a for h,a in fixtures]
ive researched and found no help for this exact attribute error, error is on line 'songs = song.split()'
any help would be greatly appreciated
score = 0
read = open("songs.txt", "r")
song = read.readlines()
songs = []
for i in range(len(songs)):
songs.append(song[i].strip('\n'))
lives = 3
while lives <=3:
for i in range(len(songs)):
songs.append(song[i].strip('\n'))
artists = song[0]
songsies = song[1]
letters = [word[0] for word in songs]
print(artists , ''.join(letters))
choice = random.choice(song)
artists ,songies = choice.split(' - ')
songs = song.split()
for i in range(len(songs)):
songs.append(song[i].strip('\n'))
print(artists, ''.join(letters))
guess = str(input('Guess the song'))
I get this error while running my code
def use(filename,option="r"):
with open(filename, option) as file:
print(file.readlines().split("\n"))my file for this example is a markdown file
The .md file is filled with random bs
# HEADER ONE
HEADER TWO
HEADER THREE
HEADER FOUR
HEADER FIVE
HEADER SIX
Some codeExamples see below:
function small(a,target){
let isValid = null;
if(a<=target>){
isValid = true;
}
else{
isValid = false;
}
console.log(`Is valid: ${isValid}`)
return a <= target
}But when I run it, I get
Traceback (most recent call last):
File "main.py", line 6, in <module>
use("a.md")
File "main.py", line 3, in use
print(file.readlines().split("\n"))
AttributeError: 'list' object has no attribute 'split'
You can use itertools.groupby (https://docs.python.org/3.6/library/itertools.html#itertools.groupby) to achieve what you want:
from itertools import groupby
grouped_data = groupby(persons_data, key=lambda x: x[1]) # or x.country, depending on your input list
for country, items in grouped_data:
# do whatever you want
There are a few gotchas to keep in mind:
groupbyreturns an iterator, so you can only iterate over it once.- the
itemsin my example above is an iterator, too. So you'll need to cast it to a list if you want to access the individual items by index later.
You can use itertools.groupby. Given persons_data is already sorted by country, the following code does what you want:
import itertools
import operator
bycountry = operator.attrgetter("country")
all_people_by_country = []
for country, groupiter in itertools.groupby(persons_data, bycountry):
all_people_by_country.append(list(groupiter))