# sum values inside a list of tuples and order by weekday [duplicate]

• Last Update :
• Techknowledgy :

With a list comprehension:

```>>> l = [('Wed', 1), ('Wed', 1), ('Thu', 1), ('Thu', 0), ('Tue', 0), ('Mon', 0), ('Sun', 0), ('Sat', 0), ('Fri', 0)] >>>
[(x, sum(y[1]
for y in l
if y[0] == x)) for x in set(z[0]
for z in l)]
[('Sun', 0),
('Tue', 0),
('Mon', 0),
('Wed', 2),
('Sat', 0),
('Thu', 1),
('Fri', 0)
]```

To sort with second element descending:

```>>> res = [(x, sum(y[1]
for y in l
if y[0] == x)) for x in set(z[0]
for z in l)] >>>
sorted(res, key = lambda x: x[1], reverse = True)[('Wed', 2),
('Thu', 1),
('Sun', 0),
('Tue', 0),
('Mon', 0),
('Sat', 0),
('Fri', 0)]```

To sort by day of week (more answers here):

```>>> sorted_days = ["Fri", "Sat", "Sun", "Mon", "Tue", "Wed", "Thu"] >>>
sorted(res, key = lambda x: sorted_days.index(x[0]))[('Fri', 0),
('Sat', 0),
('Sun', 0),
('Mon', 0),
('Tue', 0),
('Wed', 2),
('Thu', 1)]```

Suggestion : 2

Last Updated : 11 May, 2020

Output:

```The original list of tuple is[(4, 5), (2, 3), (6, 7), (2, 8)]

[(2, 3), (4, 5), (2, 8), (6, 7)]```

Suggestion : 3

Python Program To Sort a list of tuples by second Item,In this program, sorting is done using the binary sorting approach. The second member of the tuple will be used as an index for sorting the list.,Python Programs Find Most Occurring Char Python Regex to List of Tuples Display Keys associated with Values in Dictionary Find Closest Pair to Kth index element in Tuple ,Python has various built-in sorting functions. When utilizing the sorting techniques, we must provide a method that swaps the element to the second member of the tuple.

In this program, the actual content of the tuple is changed while sorting with this method. The sort() function uses the default comparisons operator between items to sort the components of a list in ascending or descending order. Instead of using the default operator, use the key argument to give the function name to be used for comparison.

```#tuple list
tuple = [(200, 6), (100, 3), (400, 12), (300, 9)]
print("Orignal Tuple List :", tuple)
#function
def Sort(tuple):
# Sorts in Ascending order
tuple.sort(key = lambda a: a[1])
return tuple

# printing the sorted list of tuples
print("Sorted Tuple List:", Sort(tuple))```

The sorted() method returns a sorted list of the iterable object that was passed in. You may choose whether to sort the results in ascending or descending order. Numbers are ordered numerically, whereas strings are arranged alphabetically.

```# Tuple
tuple = [(200, 6), (100, 3), (400, 12), (300, 9)]
print("Orignal List: ", tuple)
# Function to sort
def Sort(tuple):
# reverse = None(Sorts in Ascending order)
return (sorted(tuple, key = lambda a: a[1]))

# sorted list of tuples
print("Sorted List: ", Sort(tuple))```

In this program, sorting is done using the binary sorting approach. The second member of the tuple will be used as an index for sorting the list.

```# Creating a new tuple
tuple = [('shubh', 2), ('sinha', 4), ('tonight', 8), ('study', 6)]
print("Orignal list : ", str(tuple))

# Sorting the list of tuples using second item
Len = len(tuple)
for i in range(0, Len):
for j in range(0, (Len - i - 1)):
if (tuple[j][1] > tuple[j + 1][1]):
temp = tuple[j]
tuple[j] = tuple[j + 1]
tuple[j + 1] = temp

# sorted list
print("Sorted List : ", str(tuple))```

Suggestion : 4

Since it is a dictionary, the items are in no particular order.,It should create a dictionary with the key as the integer and the value as the number of times it is present in the list.,However, since the list of tuples is a list, and tuples are comparable, we can now sort the list of tuples. Converting a dictionary to a list of tuples is a way for us to output the contents of a dictionary sorted by key.,There is a function with the name items associated with dictionaries that returns a list of tuples, where each tuple is a key-value pair:

There is a function with the name `items` associated with dictionaries that returns a list of tuples, where each tuple is a key-value pair:

```d = {
"one": 1,
"two": 2,
"three": 3
}
k = d.items()
print(k)```

It prints `dict_items([('one', 1), ('two', 2), ('three', 3)])`. We can cast to list using `list`,

```l = list(k)
print(l)```

We can print the content of the dictionary with below code

```for key, value in list(k):
print(key, value)```

Sample Input -

`dict_tuple_func([1, 2, 3, 1, 2, 3])`

Sample Output -

```({
1: 2,
2: 2,
3: 2
}, 6)```

Suggestion : 5

A tuple may contain elements of different types, which are stored contiguously in memory. Accessing any element takes constant time, but modifying a tuple, which produces a shallow copy, takes linear time. Tuples are good for reading data while lists are better for traversals.,The functions in this module that add and remove elements from tuples are rarely used in practice, as they typically imply tuples are being used as collections. To append to a tuple, it is preferable to extract the elements from the old tuple with pattern matching, and then create a new tuple:,Tuples are intended as fixed-size containers for multiple elements. To manipulate a collection of elements, use a list instead. Enum functions do not work on tuples.,Returns a new tuple with the element appended at the end, and contains the elements in tuple followed by value as the last element.

Tuples are denoted with curly braces:

```iex > {} {}
iex > {
1,
: two,
"three"
} {
1,
: two,
"three"
}```

The functions in this module that add and remove elements from tuples are rarely used in practice, as they typically imply tuples are being used as collections. To append to a tuple, it is preferable to extract the elements from the old tuple with pattern matching, and then create a new tuple:

```tuple = {
: ok,
: example
}

# Avoid
result = Tuple.insert_at(tuple, 2, % {})

# Prefer {
: ok, atom
} = tuple
result = {
: ok,
atom,
% {}
}```
`append(tuple(), term())::tuple()`
1._
`append(tuple(), term())::tuple()`

## Examples

```iex > tuple = {
: foo,
: bar
}
iex > Tuple.append(tuple,: baz) {
: foo,: bar,: baz
}```
`delete_at(tuple(), non_neg_integer())::tuple()`
1._
`delete_at(tuple(), non_neg_integer())::tuple()`

## Examples

```iex > tuple = {
: foo,
: bar,
: baz
}
iex > Tuple.delete_at(tuple, 0) {
: bar,: baz
}```
`duplicate(term(), non_neg_integer())::tuple()`

Suggestion : 6

Jun 27, 2020

```# Print the head of the homelessness data

print(homelessness.info())

# Print the shape of homelessness
print(homelessness.shape)

# Print a description of homelessness
print(homelessness.describe())```
```# Import pandas using the alias pd
import pandas as pd

# Print a 2 D NumPy array of the values in homelessness.
print(homelessness.values)

# Print the column names of homelessness
print(homelessness.columns)

# Print the row index of homelessness
print(homelessness.index)```
```# Sort homelessness by individual
homelessness_ind = homelessness.sort_values('individuals')

# Sort homelessness by descending family members
homelessness_fam = homelessness.sort_values('family_members', ascending = False)

# Sort homelessness by region, then descending family members
homelessness_reg_fam = homelessness.sort_values(['region', 'family_members'], ascending = [True, False])```
```# Select the individuals column
individuals = homelessness['individuals']

# Select the state and family_members columns
state_fam = homelessness[['state', 'family_members']]

# Select only the individuals and state columns, in that order
ind_state = homelessness[['individuals', 'state']]```
```# Filter
for rows where individuals is greater than 10000
ind_gt_10k = homelessness[homelessness['individuals'] > 10000]

# Filter
for rows where region is Mountain
mountain_reg = homelessness[homelessness['region'] == "Mountain"]

# Filter
for rows where family_members is less than 1000
# and region is Pacific
fam_lt_1k_pac = homelessness[(homelessness['family_members'] < 1000) & (homelessness['region'] == "Pacific")]```
```# Subset
for rows in South Atlantic or Mid - Atlantic regions
south_mid_atlantic = homelessness[(homelessness['region'] == "South Atlantic") | (homelessness['region'] == "Mid-Atlantic")]

# The Mojave Desert states
canu = ["California", "Arizona", "Nevada", "Utah"]

# Filter
for rows in the Mojave Desert states
mojave_homelessness = homelessness[homelessness['state'].isin(canu)]```