I want to separate sorted numbers with "<", but can't do it.
Here is the code:
numbers = [3, 7, 5]
print(sorted(numbers), sep="<")
The * operator as mentioned by #MisterMiyagi, can be used to unpack the list variables and use the sep.
Code:
print(*sorted(numbers), sep="<")
I dont know if this is the answer you want, but I have made a python code to seperate the sorted numbers with "<" with join after I convert the numbers to strings.
As the items in the iterable must be string types, I first use a list comprehension to create a list containing each interger as a string, and pass this as input to str.join()
# Initial String
test_str = [5,1,2,3,4]
# Sorting number
sortedNum = sorted(test_str)
# Changing numbers into string
string_ints = [str(int) for int in sortedNum]
# Joining the sorted string with "<"
output = '<'.join(string_ints)
print(output)
Related
I want to extract numbers contained in an alphanumeric strings. Please help me on this.
Example:
line = ["frame_117", "frame_11","frame_1207"]
Result:
[117, 11, 1207]
You can split with special character '_' like this:
numbers = []
line = ["frame_117", "frame_11","frame_1207"]
for item in line:
number = int(item.split("_",1)[1])
numbers.append(number)
print(numbers)
import re
temp = []
lines = ["frame_117", "frame_11","frame_1207"]
for line in lines:
num = re.search(r'-?\d+', line)
temp.append(int(num.group(0)))
print(temp) # [117, 11, 1207]
Rationale
The first thing I see is that the names inside the list have a pattern. The string frame, an underscore _ and the string number: "frame_number".
Step-By-Step
With that in mind, you can:
Loop through the list. We'll use a list comprehension.
Get each item from the list (the names="frame_number" )
Split them according to a separator (getting a sublist with ["frame", "number"])
And then create a new list with the last items of each sublist
numbers = [x.split("_")[-1] for x in line]
['117', '11', '1207']
Solution
But you need numbers and here you have a list of strings. We make one extra step and use int().
numbers = [int(x.split("_")[-1]) for x in line]
[117, 11, 1207]
This works only because we detected a pattern in the target name.
But what happens if you need to find all numbers in a random string? Or floats? Or Complex numbers? Or negative numbers?
That's a little bit more complex and out of scope of this answer.
See How to extract numbers from a string in Python?
I need a count of all the emails in a list, some of the emails however are consolidated together with a | symbol. These need to be split and the emails need to be counted after splitting to avoid getting an inaccurate or low count of frequencies.
I have a list that is something like this:
test = ['abc#gmail.com', 'xyz#jad.com|abc#gmail.com', 'asd#ajf.com|abc#gmail.com', 'asdf#adh.com', 'xyz#jad.com']
I performed a set of operations to split and when I split, the pipe gets replaced by double quotes at that location so I replace the double with single quotes so I have all email ids enclosed in single quotes.
# convert list to a string
test_str = str(test)
# apply string operation to split by separator '|'
test1 = test_str.split('|')
print(test1)
--> OUTPUT of above print statement: ["['abc#gmail.com', 'xyz#jad.com", "abc#gmail.com', 'asd#ajf.com", "abc#gmail.com', 'asdf#adh.com', 'xyz#jad.com']"]
test2 = str(test1)
test3 = test2.replace('"','')
print(test3)
--> OUTPUT of above print statement: [['abc#gmail.com', 'xyz#jad.com', 'abc#gmail.com', 'asd#ajf.com', 'abc#gmail.com', 'asdf#adh.com', 'xyz#jad.com']]
How can I now obtain a count of all the emails? This is a string essentially and if it's a list, I could use collections.Counter to easily obtain a count.
I'd like to get a list like the one listed below that has the email and the count in descending order of frequency
['abc#gmail.com': 3, 'xyz#jad.com': 2, 'asd#ajf.com': 1, 'asdf#adh.com': 1]
Thanks for the help!
You can use collections.Counter with a generator expression that iterates over the input list of strings and then iterates over the sub-list of emails by splitting the strings. Use the most_common method to ensure a descending order of counts:
from collections import Counter
dict(Counter(e for s in test if s for e in s.split('|')).most_common())
This returns:
{'abc#gmail.com': 3, 'xyz#jad.com': 2, 'asd#ajf.com': 1, 'asdf#adh.com': 1}
What about iterating over the list and calling counter.update on every string? Like this:
test = ['abc#gmail.com', 'xyz#jad.com|abc#gmail.com', 'asd#ajf.com|abc#gmail.com', 'asdf#adh.com', 'xyz#jad.com']
c = Counter()
for email_str in test:
if email_str:
c.update(email_str.split('|'))
res = c.most_common()
list1 = ['192,3.2', '123,54.2']
yx = ([float(i) for i in list1])
print(list1)
This is the code I have and I am trying to learn for future reference on how to remove , within a list of string. I tried various things like mapping but the mapping would not work due to the comma within the num.
If you want to remove commas from a string use :
list1 = string.split(",")
the string variable contains your string input, you get your output in the form a list, join the list if you want the original string without the commas.
string_joined = "".join(list1)
string_joined will contain your string without the commas.
If you want your string to just remove the comma and retain the empty space at that position, your syntax :
string = string.replace(","," ")
Also, the fist two syntax I explained, can be shortened to a single syntax :
string = string.replace(",","")
Now if you want to iterate in your list of strings, consider each element(string) in your list one at a time :
for string in list1 :
<your codes go here>
Hope this answers what you are looking for.
we can do regex to remove the non-digits to get rid of other characters
import regex as re
print([float(re.sub("[^0-9|.]", "", s)) for s in list1])
without regex:
[float(s.replace(',','')) for s in list1 ]
output:
[1923.2, 12354.2]
Here's my code:
def Descending_Order(num):
return int(''.join(sorted(str(num).split(), reverse = True)))
print Descending_Order(0)
print Descending_Order(15)
print Descending_Order(123456789)
"num" is supposed to be printed in descending order, but the code doesn't work, although I don't have any errors. Any idea why it isn't being executed?
The split is superfluous, redundant and the cause of your problem. The split method of a string requires a delimiter which in your case there is none so defaults to consecutive whitespace. As your string does not have consecutive white-space, it results in a single list containing the number in string format as the only element.
>>> str('123456789').split()
['123456789']
Sorting the resultant list is invariant as what you are sorting is a list of a single element
>>> sorted(['123456789'])
['123456789']
Finally joining and converting it to an integer restores the original number
>>> int(''.join(sorted(['123456789'])))
123456789
It is worth mentioning that sorted expects a sequence, so a string would qualify enough to be sorted without splitting into individual digits
What you probably wanted is
>>> def Descending_Order(num):
return int(''.join(sorted(str(num), reverse = True)))
>>> print Descending_Order(123456789)
987654321
You can also split the numbers using list, then sort the list that way:
def Descending_Order(num):
digits = [digit for digit in list(str(num))]
return int("".join(sorted(digits, reverse = True)))
# Output
>>> Descending_Order(123456789)
987654321
Given a long string such as:
"fkjdlfjzgjkdsheiwqueqpwnvkasdakpp"
or
"0.53489082304804918409853091868095809846545421135498495431231"
How do I find the value of the nth character in that string? I could solve this if I could convert it into a list (where each digit gets it's own index) but since the numbers aren't separated by commas I don't know how to do this either.
AFAIK there is no command like string.index(10) which would return the 11th character in.
strings are like lists. so you can access them the same way,
>>> a = "fkjdlfjzgjkdsheiwqueqpwnvkasdakpp"
>>> print a[10]
k
Strings are iterable and indexable (since it is a sequence type), so you can just use:
"fkjdlfjzgjkdsheiwqueqpwnvkasdakpp"[10]
To get the corresponding character in the nth value, just use this function:
def getchar(string, n):
return str(string)[n - 1]
Example usage:
>>> getchar('Hello World', 5)
'o'