Grab the Bottle for FREE, Destiny 2 & CyberCry Deals
Grab the Bottle FREEbie
[freebies.indiegala.com] Grab the Bottle and the FREEbie! In this quirky puzzle game you will have to solve puzzles by stretching your arm through the level.
Explore the cursed depths of a nightmare while finding powerful weapons and improving your abilities in this retro first person shooter that breaches the wall between the classics and modern sensibilities.
In day-to-day situations Japan uses the same calendar as most of the world, according to which we are currently in the year 2019 (of the common era). For official and formal documents, the Japanese calendar uses the same day and month but an era name and years-within-that-era instead of the common e...
Posted by: xSicKxBot - 04-18-2022, 07:22 AM - Forum: Python
- No Replies
How to Sort a List of Tuples by Second Value
In this article, you’ll learn how to sort a list of tuples by the second value in Python.
To make it more fun, we have the following running scenario:
BridgeTech is a bridge restoration company. They have asked you to sort and return the Top 10 elements from the Periodic Table based on the ‘Atomic Radius’ in descending order.
The atomic radius of a chemical element is a measure of the size of its atom, usually the mean or typical distance from the center of the nucleus to the outermost isolated electron.
Before any data manipulation can occur, one (1) new library will require installation.
The Pandas library enables access to/from a DataFrame.
To install this library, navigate to an IDE terminal. At the command prompt ($), execute the code below. For the terminal used in this example, the command prompt is a dollar sign ($). Your terminal prompt may be different.
$ pip install pandas
Hit the <Enter> key on the keyboard to start the installation process.
If the installation was successful, a message displays in the terminal indicating the same.
Feel free to view the PyCharm installation guide for the required library.
Add the following code to the top of each code snippet. This snippet will allow the code in this article to run error-free.
import numpy as np
from operator import itemgetter
Note: The operator library is built-in to Python and does not require installation.
Method 1: Use Sort and a Lambda
To sort a list of tuples based on the second element, use sort() and lambda in the one-liner expression tups.sort(key=lambda x: x[1], reverse=True).
Here’s an example:
df = pd.read_csv('periodic_table.csv', usecols=['Name', 'AtomicRadius'])
tups = [tuple(x) for x in df.values.tolist()]
tups.sort(key=lambda x: x[1], reverse=True)
print(tups[0:10])
The CSV file is read in preparation, and two (2) columns save to a DataFrame. The DataFrame then converts to a list of tuples (tups) using List Comprehension.
We are ready to sort!
A lambdais passed as a parameter to sort() indicating the sort element (x[1]), and the sort order is set to descending (reverse=True). The results save to tups.
To complete the process, slicing is performed, and the Top 10 elements are sent to the terminal.
To sort a list of tuples by the second element, use the sort() and itemgetter() functions in the expression tuples.sort(key=itemgetter(1), reverse=True).
Here’s an example:
df = pd.read_csv('periodic_table.csv', usecols=['Name', 'AtomicRadius'])
tups = [tuple(x) for x in df.values.tolist()]
tups.sort(key=itemgetter(1), reverse=True)
print(tups[0:10])
The CSV file is read in preparation, and two (2) columns save to a DataFrame. The DataFrame then converts to a List of Tuples (tups) using List Comprehension.
We are ready to sort!
The sort() function passes a key (itemgetter(n)) where n is the sort element (itemgetter(1)), and the sort order is set to descending (reverse=True).
The results save to tups.
To complete the process, slicing is performed, and the Top 10 elements are sent to the terminal.
Note: The itemgetter() function is slightly faster than a lambda. Use itemgetter if speed and memory are a factor.
Method 3: Use Sorted & Lambda
To sort a list of tuples by the second element, combine the functions sorted() and lambda in the expression sorted(tups, key=lambda x:(x[1]), reverse=True) and assign the resulting sorted list to the original variable tups.
Here’s an example:
df = pd.read_csv('periodic_table.csv', usecols=['Name', 'AtomicRadius'])
tups = [tuple(x) for x in df.values.tolist()]
tups = sorted(tups, key=lambda x:(x[1]), reverse=True)
print(tups[0:10])
The CSV file is read in preparation, and two (2) columns save to a DataFrame. The DataFrame then converts to a List of Tuples (tups) using List Comprehension.
We are ready to sort!
A lambdais passed as a parameter to sorted(), indicating the sort element (x[1]), and the sort order is set to descending (reverse=True). The results save to tups.
To complete the process, slicing is performed, and the Top 10 elements are sent to the terminal.
Method 4: Use Bubble Sort
To sort a List of Tuples by the second element, you can also modify a sorting algorithm from scratch such as Bubble Sort to access the second (or n-th) tuple value as a basis for sorting.
Here’s an example:
df = pd.read_csv('periodic_table.csv', usecols=['Name', 'AtomicRadius'])
tups = [tuple(x) for x in df.values.tolist()] def sort_tuples_desc(tups, idx): length = len(tups) for i in range(0, length): for j in range(0, length-i-1): if (tups[j][idx] < tups[j + 1][idx]): tmp = tups[j] tups[j] = tups[j+1] tups[j+1] = tmp return tups
print(sort_tuples_desc(tups, 1)[0:10])
The CSV file is read in preparation, and two (2) columns save to a DataFrame. The DataFrame then converts to a List of Tuples (tups) using List Comprehension.
We are ready to sort!
A sort function sort_tuples_desc is created and passed two (2) parameters: a List of Tuples (tups), and the sort element (idx). Then, the infamous Bubble Sort is performed on the elements.
This function returns a List of Tuples sorted in descending order.
To complete the process, slicing is performed, and the Top 10 elements are sent to the terminal.
Summary
These four (4) methods of sorting a List of Tuples based on the second element should give you enough information to select the best one for your coding requirements.
[www.indiegala.com] Your favorite Nickelodeon shows, G.I. Joe, Cobra Kai, Street Outlaws, Goosebumps are made into videogames that are now made into giveaways!
[www.indiegala.com] HELLDIVERS™ is a hardcore, cooperative, twin stick shooter. Work together to protect SUPER EARTH and defeat the enemies of mankind in an intense intergalactic war.
Save a Tokyo under siege by spirits in a new adventure from mastermind Shinji Mikami and the team at Tango Gameworks. Explore the streets of a city filled with spirits and mysterious otherworldly threats, with an arsenal of powerful abilities at your command.
Tokyo has become a city under siege; overwhelmed by paranormal threats beyond our understanding. After a devastating occult event leads to the disappearance of 99% of the city's population, only you stand between the loss of this great city and its salvation. After the vanishing, a strange encounter causes your own supernatural abilities to take shape. Explore a beautiful city that blends ultra-modern cityscapes and stunning ancient shrines as you purge the darkness from your home. Armed with a bevy of formidable, upgradeable powers, you will face off against evil spirits (referred to as The Visitors) haunting the city of Tokyo.
Spirits like:
* Amewarashi: This entity manifests as a young child in a yellow raincoat. Derived from the powerful emotions of sadness caused by being separated from his parents, as well as his innocent yet mischievous spirit, this Visitor will call for help and bring forth fellow spirit when it feels threatened.
* Shiromuku: Shiromuku is a traditional type of pure white wedding kimono, and though she may appear to be a bride, this Visitor is actually a physical manifestation of powerful emotions. This Visitor represents regret and strong feelings for a partner she was never able to marry.
* Kuchisake: Inspired by an actual urban legend, the Kuchisake-onna is a strong and agile opponent, capable of closing distances quickly to get at you with her large scissor blades. Be careful if she asks you if you find her attractive; there are no right answers there.
Each spirit will have its own attack styles and weaknesses, so you'll need to combine your abilities in different ways to suit each unique combat encounter.
But the spirits roaming the streets aren't the only threat. At the heart of everything the disappearance of the population, the appearance of the Visitors, and even your own supernatural abilities sits a shadowy group wearing "Hannya" masks. Who are they, what they want and how they will interact with you remains a mystery, and it will be up to you to determine their motives and unveil the mystery.
Posted by: xSicKxBot - 04-18-2022, 07:22 AM - Forum: Lounge
- No Replies
Halo Infinite's Two New Season 2 Maps Couldn't Be More Different
Halo Infinite Season 2: Lone Wolves will be here in just a few weeks, and 343 Industries has revealed the two new maps Spartans will be murdering each other on. Named Cataylst and Breaker, the maps are very different from one another, with one focusing on cold, industrial interiors while the other is an open desert map designed for Big Team Battle.
For fans of traditional arena-style multiplayer, you can look forward to Catalyst. In a blog post on Halo Waypoint, multiplayer level designer Tyler Ensrude described it as a "tunnel-like" map with Forerunner structures, complete with the light bridge we've come to know and love from Halo. It shares some similarities with Epitaph from Halo 3 and the ever-popular Haven from Halo 4, but with a scrappier feel. There is more Banished influence, as the group relies heavily on captured technology and weapons rather than its own creations.
Breaker is an open outdoor map designed for Big Team Battle, especially CTF matches, with a base on either side making for huge skirmishes in the midsection. Huge pieces of wrecked machinery are visible here, building on what you see throughout Halo Infinite's campaign. There's even a "death pit" that you can jump in a Warthog if you are skilled enough, but hitting the ramp incorrectly will result in a very unceremonious death.
JDK 12 is live! Download it from the Java SE Downloads page. See the JDK 12 Release Notes for detailed information about this release. The following are some of the important additions and updates in Java SE 12 and JDK 12: JVM Constants API is introduced to model nominal descriptions of key class-fi...
Posted by: xSicKxBot - 04-17-2022, 11:31 AM - Forum: Python
- No Replies
Writing a List to a File in Python
Table of Contents
Problem Statement: How to write a list to a file with Python?
Mostly Python programmers use persistent storage systems like databases or files to store serialized data structures like arrays, lists, and dictionaries. It is because databases and files are reusable, i.e. after analyzing the given data, we can store it in the file, and later that data can be read to use in an application. There are many different ways to write a list to the file in Python. Let’s look at some of them:
Method 1- Using Read And Write
Python facilitates us with standard methods used to read the data from the file and to write the data to a file. While dealing with single lines, we can use the read() and write() methods, respectively. Suppose we have the following list of strings and we have to store each string in a file using Python:
To write the list in to file, we have to follow the steps given below:
Firstly, open the file in write mode by passing the file path and access mode “w” to the open() function.
Next, we have to use the “for” loop to iterate the list. In each iteration, we will get a list item that we need to write in the file using the write() method.
After iterating through the whole list, we need to ensure that we have closed the file. For that, we use the close() method.
Let’s visualize the above demonstration with the help of the following snippet:
# List of colours
colors = ["red", "black", "white", "yellow", "blue"]
# Opening the file in write mode
file = open('colors.txt', 'w')
# Writing the list to the file
for color in colors: file.write(color + '\n')
# Closing the file
file.close()
Output:
red black white yellow blue
Note: The ‘\n‘ character is used for a new line at the end of each item in the list.
Let’s have a look at a situation that demonstrates how we can read the list from the file:
Example:
# Empty list that will read from the file
colors = []
# Opening the file in read mode
with open(r'colors.txt', 'r') as file: for color in file: x = color[:-1] colors.append(x)
print(colors)
While dealing with multiple lines, we have to use the readlines() and writelines() file methods in Python. Hence we can write the entire list into a file using the writelines() method.
Example:
# List of colours
colors = ["red", "black", "white", "yellow", "blue"]
# Opening the file in write mode
with open('colors.txt', 'w') as file: # Writing the entire list to the file file.writelines("\n" % color for color in colors)
Output:
red black white yellow blue
⦿ The following example shows how to use readlines() to read the entire list from a file in Python:
Example:
# Empty list that will read from the file
colors = []
# Opening the file in read mode
with open(r'colors.txt', 'r') as file: colors = [color.rstrip() for color in file.readlines()]
Output:
["red", "black", "white", "yellow", "blue"]
Method 3- Using The Pickle Module
Pickle is a module in Python that is used to serialize or de-serialize an object structure. We can use this module to serialize a list for later use in the same file. The dump() method from the module is used to write the list into a file and it takes the reference of the file and list as its parameters. The method stores the list efficiently as a binary data stream. As it uses a binary stream, the file can even be opened in binary writing mode (wb). Using the module, we can convert any object like a list or dictionary into a character stream. The character stream has the information to reconstruct the object in the future.
Approach: To write a list into the file, we have to first import the pickle module at the start of the program. Then we will use the access mode to open the file. The open() function checks if the file exists or not and if it exists, it gets truncated. The function creates a new one if the file doesn’t already exist. Further, the dump() method converts the object and writes it into the file.
Example:
# Importing the pickle module
import pickle
# Writing the list to the binary file
def writel(a): # Storing the list in binary file (wb) mode with open('file', 'wb') as fp: pickle.dump(colors, fp) print('Completed the process of writing the list into a binary file')
# Reading the list to memory
def readl(): # Reading the list in binary file (rb) mode with open('sample', 'rb') as fp: n = pickle.load(fp) return n
# List of colors
colors = ["red", "black", "white", "yellow", "blue"]
# Calling the writel method
writel(colors)
color = readl()
# Printing the list
print(color)
Output:
Completed the process of writing the list into a binary file ["red", "black", "white", "yellow", "blue"]
Method 4- Using The Json Module
We can use the JSON module to convert the list into a JSON format and then write it into a file using the JSON dump() method. Generally, when we execute a GET request, we will receive a response in JSON format. We can then store the JSON response in a file for any future use.
# Importing the JSON module
import JSON
def writel(a): with open("colors.json", "w") as fp: json.dump(a, fp) print('Completed the process of writing json data into json file')
# Reading the list to memory
def readl(): with open('colors.json', 'rb') as fp: n = json.load(fp) return n
# List of colors
colors = ["red", "black", "white", "yellow", "blue"]
writel(colors)
color = readl()
# Printing the list
print(color)
Output:
Completed the process of writing json data into json file ["red", "black", "white", "yellow", "blue"]
Conclusion
That’s all about how to write a list to a file with Python. I hope you found it helpful. Please stay tuned and subscribefor more interesting articles. Happy learning!
Days Gone: A Historical Crackerjack Steam Key Deal
[www.indiegala.com] Step into the dirt flecked shoes of former outlaw biker Deacon St. John, a bounty hunter surviving in an open-world action-adventure game set in the harsh wilderness of Days Gone.