The file contents are:
min:1,2,3,4,5,6
max:1,2,3,4,5,6
avg:1,2,3,4,5,6
Code:
def avg_calc():
total = 0
nums_inLine = line[4: -1]
num_list = []
num_list = nums_inLine.split(',')
length = len(num_list)
print(num_list)
with open('input.txt', 'r', encoding='utf-8-sig') as in_file:
content = in_file.readlines()
for line in content:
if 'min' in line:
min_calc()
elif 'max' in line:
max_calc()
elif 'avg' in line:
avg_calc()
My problem is that the '6' in the third line disappears or replaced by a whitespace. Why does it do that?
Output:
['1', '2', '3', '4', '5', '']
final goal is to cast each element in the list to an int then perform calculations to calculate the average of the numbers.
Related
I have a list, where I want to group the repeating objects into a single object in the new list. Basically, convert this:
s = ['0.352125', '1', '1', '1', '1', '0', '0', '0', '0', '0', '0', '0', '0', '0.241041', '0.313429', '1', '1']
to this:
s_new = ['0.352125', '4*1','8*0', '0.241041', '0.313429','2*1']
I have tried itertools.groupby() function (python 2.7) as below:
from itertools import groupby
s_g = [list(g) for k, g in groupby(s)]
s_new = [', '.join('{}*{}'.format(sum(1 for _ in g), k) for k, g in groupby(s_g))]
As a result, I get:
s_new = ["1*['0.352125'], 1*['1', '1', '1', '1'], 1*['0', '0', '0', '0', '0', '0', '0', '0'], 1*['0.241041'], 1*['0.313429'], 1*['1', '1']"]
Apparently, this is not the list format I'm trying to get. Could someone please help me with this?
You unnecessarily applied groupby twice and there's also no reason to use str.join.
You can use the following list comprehension instead:
['%s*' % len(l) * (len(l) > 1) + k for k, g in groupby(s) for l in (list(g),)]
import re
fhand = open('sum.txt','r')
number = re.findall('[0-9]'+, fhand)
print number
I am getting syntax error as
number = re.findall('[0-9]'+, fhand)
^
SyntaxError: invalid syntax
Not sure what's going on. Can anybody help?
Read the file contents and declare the entire pattern inside a string literal.
Here is an example:
>>> import re
>>> fhand = open(r'D:\2\_1.txt','r')
>>> fhand
<open file 'D:\\2\\_1.txt', mode 'r' at 0x0282B230>
>>> number = re.findall('[0-9]+', fhand.read())
>>> print number
['1', '2', '3', '1', '0', '2', '0', '7', '0', '2', '2', '0', '3', '0', '5', '0', '3']
>>>
I need to make a function that receives a string of numbers and the ouput is the letters that correspond to those numbers, like if you are sending a message on a cell phone. For example to get the letter 'A' the input should be '2', to get the letter 'B', the input should be '22', etc. For example:
>>>number_to_word('222 '233' '3'):
"CAFE"
The program needs to "go around" the number if the limit of the number is reached. For example, the letter 'A', can be these following inputs: '2', '2222','2222222', etc. Just like if your sending a text message on cell phone when you get pass 'C' ( which is'222' ) the program goes again to 'A', making '2222' it's key. Also, in the input, if the string is '233' the program must separate the different numbers, so this ('233') will be equal this ('2' '33')
I made a dictionary like this:
dic={'2':'A', '22':'B', '222':'C', '3':'D', '33':'E', '333':'F',..... etc}
But I don't know how to make the program "go around" if the input is '2222', and how do I take that number and assign it to the letter 'A'.
Feel free to ask any questions if you don't understand what I'm asking I would be glad to explain it with more detail. Thank you.
This seems to give the desired result:
NUMBERS = {'2': 'A', '22': 'B', '222': 'C', '3': 'D', '33':'E', '333': 'F'}
def normalize_number(number):
for item in number.split():
if len(set(item)) == 1:
yield item
else:
last = item[0]
res = [last]
for entry in item[1:]:
if entry == last:
res.append(entry)
else:
yield ''.join(res)
res = [entry]
last = entry
yield ''.join(res)
def number_to_word(number):
res = []
for item in normalize_number(number):
try:
res.append(NUMBERS[item])
except KeyError:
if len(item) >= 4:
end = len(item) % 3
if end == 0:
end = 3
res.append(NUMBERS[item[:end]])
return ''.join(res)
Test it:
>>> number_to_word('222 2 333 33')
'CAFE'
>>> number_to_word('222 2 333 3333')
'CAFE'
>>> number_to_word('222 2 333 333333')
'CAFE'
>>> number_to_word('222 2333 3333')
'CAFE'
The function normalize_number() turns numbers that have different digits into multiple numbers with only the same digit:
>>> list(normalize_number('222 2 333 3333'))
['222', '2', '333', '3333']
>>> list(normalize_number('222 2333 3333'))
['222', '2', '333', '3333']
>>> list(normalize_number('222 2 333 53333'))
['222', '2', '333', '5', '3333']
I have a list that i need to write to a .csv Yes, i have done a LOT of looking around (of course i found this link which is close to the target, but misses my case) You see writerows is having all sorts of trouble with the delimiters/formatting in the .csv (the a gets separated from the 1 from the 7 etc etc)
My list looks like this:
buffer = [['a17', 'b17', 'c17', '8', 'e17', 'f17\n'], ['a24', 'b24', 'c24', '6', 'e24', 'f24\n'], ['a27', 'b27', 'c27', '9', 'e27', 'f27\n'], ['a18', 'b18', 'c18', '9', 'e18', 'f18\n'], ['a5', 'b5', 'c5', '5', 'e5', 'f5\n'], ['a20', 'b20', 'c20', '2', 'e20', 'f20\n'], ['a10', 'b10', 'c10', '1', 'e10', 'f10\n'], ['a3', 'b3', 'c3', '3', 'e3', 'f3\n'], ['a11', 'b11', 'c11', '2', 'e11', 'f11\n']]
I can see its like a list of lists so i tried for eachRow in buffer: then following on with a eachRow.split(',') but no good there either.
I just need to write to a .csv it should be easy right... what am i missing?
You can remove the \n string from your buffer like so. Also you have to add newline='' to the with statement in Python 3. See this answer for more detail.
import csv
buffer = [['a17', 'b17', 'c17', '8', 'e17', 'f17\n'],
['a24', 'b24', 'c24', '6', 'e24', 'f24\n'],
['a27', 'b27', 'c27', '9', 'e27', 'f27\n'],
['a18', 'b18', 'c18', '9', 'e18', 'f18\n'],
['a5', 'b5', 'c5', '5', 'e5', 'f5\n'],
['a20', 'b20', 'c20', '2', 'e20', 'f20\n'],
['a10', 'b10', 'c10', '1', 'e10', 'f10\n'],
['a3', 'b3', 'c3', '3', 'e3', 'f3\n'],
['a11', 'b11', 'c11', '2', 'e11', 'f11\n']]
for row_index, list in enumerate(buffer):
for column_index, string in enumerate(list):
buffer[row_index][column_index] = buffer[row_index][column_index].replace('\n', '')
with open('output.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerows(buffer)
import csv
with open('output.csv','w') as f:
writer = csv.writer(f)
writer.writerows(buffer)
Note that the last entry in each of your lists has a newline, so the csvwriter is correctly quoting the string so you end up with "f17\n" (in the first list as an example) which will look strangely formatted if you are not expecting a new line.
I have a 2D list:
[['Hard', '7', '27.00'], ['David', '4', '26.00'], ['Great', '2', '25.00']]
I want to print it out in alphabetical order based on the first index of each list. I have a variable called listName which stores the information as presented above. I have tried listName.sort() however, it does not sort in alphabetical order. Any suggestions?
You have to pass a key argument to sort(). This function will sort the elements (in your case, each element is a list) based on the first item (x[0]) of that element:
listName.sort(key = lambda x:x[0])
Note: This will sort the lists based on an ASCII comparison (please, correct me if I'm wrong), therefore, it will put uppercase before lowercase. For example:
listName = [['Hard', '7', '27.00'], ['David', '4', '26.00'], ['Great', '2', '25.00'], ['a', '3', '123']]
listName.sort(key = lambda x:x[0])
print(listName)
# [['David', '4', '26.00'], ['Great', '2', '25.00'], ['Hard', '7', '27.00'], ['a', '3', '123']]
Two more options:
# The data
listName = [['Hard', '7', '27.00'], ['David', '4', '26.00'], ['Great', '2', '25.00'], ['a', '3', '123']]
# Use first element for sorting using operator.itemgetter (like x[0])
from operator import itemgetter
sorted(listName, key=itemgetter(0))
# Use a function instead of a lambda (+ case insensitive sorting)
def get(x):
# return first element of sublist and convert to lowercase
return x[0].lower()
sorted(listName, key=get)
Lambdas and function are very similar:
lambda x: x[0]
def get(x): return x[0]
The difference is that functions have a name and lambdas are anonymous (unless stored in a variable). You must not use return in a lambda, its behavior is always like there is one.