I am trying to write output of one list to another and I opened an empty list and did an .append(). How ever it gives me an error? I Have mentioned the error below.
What I need?:
the output of list 1 should be put into list 2, shuffle all the lines in list 2 and write that output to a file called random_lines.
def main():
c = int(sys.argv[1])
if c == 1:
rep()
elif c == 2:
Line()
def rep():
n = int(sys.argv[2])
m = int(sys.argv[3])
count = 0
with open(sys.argv[4]) as f:
list1 = random.sample(f.readlines(),n)
list2 = []
while (count<m):
for i in list1:
list2.append(list1)
count+=1
random_lines = random.shuffle(list2)
with open(sys.argv[5],"w") as outcsv:
print >> outcsv, ''.join(random_lines)
print >> outcsv, ''.join(random_lines)
TypeError: can only join an iterable
What mistake am i making?
Related
I have an array like this:
A = [0,0,3,6,6,7,8,11,11,22]
And I want to remove the elements that appear an even number of times inside the array, so you get:
res = [3,7,8,22]
Is this possible using numpy?
Actually you don't need numpy for this type of array manipulation. I tried using pure python.
def removeevencountelements(listarg) :
minelement = min(listarg)
maxelement = max(listarg)
uniqueelementsset = set(listarg)
outputlist = [ ]
for i in range(0 , len(uniqueelementsset)) :
if ((listarg.count((list(uniqueelementsset)[i]))) % 2 == 1) :
for i2 in range((listarg.count((list(uniqueelementsset)[i])))) :
outputlist.append((list(uniqueelementsset)[i]))
return outputlist
A = [1,1,1,2,2,3,5,7,8,9,10,10,10,10,12,12,12,15,1]
print(removeevencountelements(A))
Another way to implemet it, using a dictionary (only looping at most twice on all elements):
def f1(arr):
result = []
counter_dict = {}
for num in arr:
if num in counter_dict:
counter_dict[num] += 1
else:
counter_dict[num] = 1
for key in counter_dict:
if counter_dict[key] % 2 == 1:
result.append(key)
return result
edit: If you need to keep all original appearances of the array then this works:
def f2(arr):
result = []
counter_dict = {}
for num in arr:
if num in counter_dict:
counter_dict[num] += 1
else:
counter_dict[num] = 1
for key in counter_dict:
if counter_dict[key] % 2 == 1:
result.extend([key]*counter_dict[key])
return result
input: A = [0,0,3,6,6,7,8,11,11,22,22,22]
output f1: [3,7,8,22]
output f2: [3,7,8,22,22,22]
Here is a very simple way to accomplish this:
resultArray = [a for a in arr if arr.count(a) % 2 != 0]
where 'arr' is your original array.
import os; import time;
not_command_error = "error: not an command"
empty_error = "error: file empty"
def read(file):
e = open(file, "r")
b = e.readlines()
e.close()
return b
code_file = "put your code here"
e = read(code_file)
if e == []:
print("\033[0;37;41m",empty_error)
time.sleep(90000)
count = len(e)
print(count)
g = 0
l = 0
while True:
l+= 1
t = open(code_file, "r")
y = t.readlines(l)
t.close()
k = len(y)
print(y[k])
u = y[k]
g+= 1
if count == g:
break
this is my code, and I get and index out of range error, any help?
i tried changing the format and it still didn't work.
i get index out of range error, do i not use a variable?
This part of your code will throw an index out of range error:
k = len(y)
print(y[k])
Indices for lists in Python go from 0 to len(x) - 1, so to access the last element, k should equal len(y) - 1.
Even better (thanks, #MarkK!), you can use negative indices to access the end of the array:
print(y[-1])
I am writing some code to print high scores from a file. I am new to python and therefore don't have much experience. It'd be great to be told where I am going wrong and how to fix it :)
Please note the code may not be efficient!!!
Searching up the problem and looking to friends for advice, coming from a background with no prior coding knowledge, no one around me knows how to help!
file = open("scores.txt", "r")
for line in file:
filecont = line.split(",")
listOfInt = filecont[::2]
listOfStr = filecont[1::2]
intoDict = zip(listOfStr, listOfInt)
dictOfWords = dict(intoDict)
sortedbyValueDict = sorted(dictOfWords.items(), key = lambda t:t[1])
print("\n<<< HIGH SCORES >>>\n")
counter = 0
for i in sortedbyValueDict:
print(i, ':', sortedbyValueDict[i])
counter = counter + 1
if counter == 5:
break
Scores.txt is as follows:
7,jacob,5,rishikesh,3,alex,2,oliver,9,piers
I expect the output to be a sorted print of the top 5 high scores in order, however I am getting the error message:
TypeError: list indices must be integers or slices, not tuple
Thank you anyone who helps!
Try this
import sys
file = open("input.txt", "r")
for line in file:
filecont = line.split(",")
listOfInt = filecont[::2]
listOfStr = filecont[1::2]
intoDict = zip(listOfStr, listOfInt)
dictOfWords = dict(intoDict)
print(dictOfWords)
sortedbyValueDict = sorted(dictOfWords.items(), key = lambda t:t[1], reverse=True)
print("\n<<< HIGH SCORES >>>\n")
counter = 0
for i in sortedbyValueDict:
print(counter, ':', i)
counter = counter + 1
if counter == 5:
break
This will give you the result:
<<< HIGH SCORES >>>
0 : ('piers', '9')
1 : ('jacob', '7')
2 : ('rishikesh', '5')
3 : ('alex', '3')
4 : ('oliver', '2')
You can remove reverse=True if you want it in ascending order.
You are confusing two different types of iterations.
When you run the following:
l = ['A', 'B', 'C']
for i in l:
print(i)
The output will be:
A
B
C
If you want to treat i as an integer like in most other languages, you need to use the range function:
for i in range(3):
print(i)
output:
0
1
2
if you want to iterate over a list in this manner, you need to combine range with the len function, which returns the length of a list:
for i in range(len(l)):
print(l[i])
output:
A
B
C
In your case, the following will fix your error:
for i in sortedbyValueDict:
print(i)
counter = counter + 1
if counter == 5:
break
or:
for i in range(len(sortedbyValueDict)):
print(i, ':', sortedbyValueDict[i])
counter = counter + 1
if counter == 5:
break
I've written some code that can parse a string into tuples as such:
s = '30M3I5X'
l = []
num = ""
for c in s:
if c in '0123456789':
num = num + c
print(num)
else:
l.append([int(num), c])
num = ""
print(l)
I.e.;
'30M3I5X'
becomes
[[30, 'M'], [3, 'I'], [5, 'X']]
That part works just fine. I'm struggling now, however, with figuring out how to get the values from the first column of a tab-separated-value file to become my new 's'. I.e.; for a file that looks like:
# File Example #
30M3I45M2I20M I:AAC-I:TC
50M3X35M2I20M X:TCC-I:AG
There would somehow be a loop incorporated to take only the first column, producing
[[30, 'M'],[3, 'I'],[45, 'M'],[2, 'I'],[20, 'M']]
[[50, 'M'],[3, 'X'],[35, 'M'],[2, 'I'],[20, 'M']]
without having to use
import csv
Or any other module.
Thanks so much!
Just open the path to the file and iterate through the records?
def fx(s):
l=[]
num=""
for c in s:
if c in '0123456789':
num=num+c
print(num)
else:
l.append([int(num), c])
num=""
return l
with open(fp) as f:
for record in f:
s, _ = record.split('\t')
l = fx(s)
# process l here ...
The following code would serve your purpose
rows = ['30M3I45M2I20M I:AAC-I:TC', '30M3I45M2I20M I:AAC-I:TC']
for row in rows:
words = row.split(' ')
print(words[0])
l = []
num = ""
for c in words[0]:
if c in '0123456789':
num = num + c
else:
l.append([int(num), c])
print(l)
Change row.split(' ') to ('\t') or any other seperator as per the need
something like this should do what you're looking for.
filename = r'\path\to\your\file.txt'
with open(filename,'r') as input:
for row in input:
elements = row.split()
# processing goes here
elements[0] contains the string that is the first column of data in the file.
Edit:
to end up with a list of the lists of processed data:
result = []
filename = r'\path\to\your\file.txt'
with open(filename,'r') as input:
for row in input:
elements = row.split()
# processing goes here
result.append(l) # l is the result of your processing
So this is what ended up working for me--took bits and pieces from everyone, thank you all!
Note: I know it's a bit verbose, but since I'm new, it helps me keep track of everything :)
#Defining the parser function
def col1parser(col1):
l = []
num = ""
for c in col1:
if c in '0123456789':
num = num + c
else:
l.append([int(num), c])
num = ""
print(l)
#Open file, run function on column1
filename = r'filepath.txt'
with open(filename,'r') as input:
for row in input:
elements = row.split()
col1 = elements[0]
l = col1parser(col1)
I have a question concerning some python code that I have written:
def read_graph_from_file(filename):
txtfile = open(filename, "rU")
node_memory = 0
neighbour_list = 0
for entry in txtfile:
entry_without_newline = entry.replace('\n',"")
columns = entry_without_newline.replace(','," ")
columns = columns.split(" ")
number_of_columns = len(columns)
if number_of_columns == 2:
neighbour_list = columns
neighbour_list.sort()
if node_memory == float(neighbour_list[0]):
y = neighbour_list[1]
print y
The output I want from this is a list, i.e. [1,4]. Instead I am receiving the characters across multiple lines, i.e:
1
4
I was wondering how I might rectify this?
If you want them in a list, you will have to create a list variable and just append your results to it. You should return this list once your function is done.
def read_graph_from_file(filename):
txtfile = open(filename, "rU")
node_memory = 0
neighbour_list = 0
lst = []
for entry in txtfile:
entry_without_newline = entry.replace('\n',"")
columns = entry_without_newline.replace(','," ")
columns = columns.split(" ")
number_of_columns = len(columns)
if number_of_columns == 2:
neighbour_list = columns
neighbour_list.sort()
if node_memory == float(neighbour_list[0]):
y = neighbour_list[1]
lst.append(y)
return lst
Then if you run your function like this:
print read_graph_from_file(<fileName>)
You will get the desired result:
[1,4]
Alternatively, you can print the resulting list directly at the end of your function. Then you won't have to call the function with print.