python format string by length [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have some strings below:
123123|00|992|1111
222222|2222|19|922
997997|3333|922|77
How can I format like this (sort by len):
123123|1111|00|992
222222|2222|19|922
997997|3333|77|922

Using str.split & str.join with sorted
Demo:
s = """123123|00|992|1111
222222|2222|19|922
997997|3333|922|77"""
data = ["|".join(sorted(i.split("|"), key=len, reverse=True)) for i in s.split("\n")]
print( "\n".join(data) )
Output:
123123|1111|992|00
222222|2222|922|19
997997|3333|922|77

Try this
a='''123123|00|992|1111
222222|2222|19|922
997997|3333|922|77'''
'\n'.join(['|'.join(sorted(e.split("|"),key=len,reverse=True)) for e in a.split("\n")])
Output:
123123|1111|992|00
222222|2222|922|19
997997|3333|922|77

The OPs sort order isn't based on string length, as the length of 2 comes before the length of 3 (the very last two segments)
for that purpose, a custom sort mapping is needed
ranks = {6:0, 4:1, 2:2, 3:3}
text = """123123|00|992|1111
222222|2222|19|922
997997|3333|922|77"""
result = '\n'.join(['|'.join(sorted(line.split('|'),key=lambda x: ranks[len(x)]))
for line in text.split('\n')])
print(result)
# outputs:
123123|1111|00|992
222222|2222|19|922
997997|3333|77|922

Related

The output for floats in list of tuples [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have the list of sorted tuples, containing floats. But when I try to output the floats (without commas and brackets) it output separate tuples BUT with brackets and commas, which I do not need.
This is the part of the code:
data=[tuple1, tuple2, tuple3, tuple4]
a=sorted(data, key = lambda x: (x[0], x[1]))
b="\n".join(map(str,a))
print(b)
try this:
data=[tuple1, tuple2, tuple3, tuple4]
s=''
for i in range(len(a)):
for j in a[i]:
s += str(j)
print(s)
Try this:
print('\n'.join(' '.join(map(str, x)) for x in a))

Efficient way of parsing string [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
How would you turn a string that looks like this
7.11,8,9:00,9:15,14:30,15:00
into this dictionary entry
{7.11 : [8, (9:00, 9:15), (14:30, 15:00)]}?
Suppose that the number of time pairs (such as 9:00,9:15 and 14:30,15:00 is unknown and you want to have them all as tuple pairs.
First split the string at the commas, then zip cluster starting from the 3rd element and put it into a dictionary:
s = "7.11,8,9:00,9:15,14:30,15:00"
ss = s.split(',')
d = {ss[0]: [ss[1]] + list(zip(*[iter(ss[2:])]*2))}
Output:
{'7.11': ['8', ('9:00', '9:15'), ('14:30', '15:00')]}
If you need to convert it from string to appropiate data types (you'll have to adapt it according to your needs), then after getting the ss list:
time_list = [datetime.datetime.strptime(t,'%H:%M').time() for t in ss[2:]]
d = {float(ss[0]): [int(ss[1])] + list(zip(*[iter(time_list)]*2))}

replace multi words using dictionary [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
import re
dic={}
dic1={}
s="ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR `COUNTRY"
sentence=". ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU"
sentence0=". ASK WHAT YOU CAN DO FOR YOUR COUNTRY"
sentence2=sentence.split()
sentence1=sentence.split()
for position,char in enumerate(sentence1):
dic[(char)]=(position)
for position,char in enumerate(sentence2):
dic1[(char)]=(position)
dic.update(dic1)
del dic["."]
print(dic)
pattern = re.compile(r'\b(' + '|'.join(dic.keys()) + r')\b')
result = pattern.sub(lambda x: dic[x.group()], s)
print(result)
When I run the program I have these error TypeError: sequence item 0: expected str instance, int found.How can I solve it?
You need a string for the sub function, to fix that you can either change the dictionary's values to strings:
dic1[(char)]=str(position)
or change the lambda function to:
result = pattern.sub(lambda x: str(dic[x.group()]), s)

How can I check the items in the list on the similarities python? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
How can I check the items in the list on the similarities in python?
I have input list, which was created:
a = input()
list = []
list += a
so if i'll have aabbbc the result which i'll need 2a3b1c
You can use collections.Counter to do the actual counting. Then use a generator expression with some string operations to format the result as you'd like.
>>> from collections import Counter
>>> ''.join(str(v) + k for k,v in sorted(Counter('aabbbc').items()))
'2a3b1c'
Use Counter
from collections import Counter
result = Counter('aabbbc')
print(result)

Python using str as bytearray [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I'm trying to implement a Reed-Solomon encoder.
I start with a list of bytearray and then I have to convert all the elements of the list into str.
So now I have this list: ["bytearray(b'XXXXXXX')"]
But I have to retrieve the value from the list: "bytearray(b'XXXXXXX')" as a bytearray: bytearray(b'XXXXXXX')...
How can I perform this conversion?
I don't think you're doing it right...
If you want to convert all list elements to str, you'd use the bytearray.decode method:
In [10]: lst = [bytearray(b'XXXXXXX')]
In [11]: newlst = [x.decode('ascii') for x in lst]
In [12]: newlst
Out[12]: ['XXXXXXX']
And the reverse of that is
In [13]: [bytearray(s, 'ascii') for s in newlst]
Out[13]: [bytearray(b'XXXXXXX')]

Categories