Printing an array of floats in a certain format - python

I have a problem writing the following arrays to a .txt file.
This is my code:
for i in range(len(my_particles)):
list = []
list.append(my_particles[i].n)
for z in range(len(my_particles[i].neighbours)):
list.append(my_particles[i].neighbours[z])
#for i in range(len(list)):
print >>f, list
f.close()
This is the output:
[0, 2, 20, 91, 114, 127]
[1, 6, 24, 114]
[2, 0, 65, 73, 91, 114]
[3, 71, 91, 120]
[4, 16, 69, 104]
[6, 1, 25, 87, 100, 114]
[7, 19, 83, 111]
[9, 38, 59, 72, 76]
[11, 56, 101, 108]
[12, 86, 92, 126]
[13, 30, 79, 82, 101, 104]
[14, 78, 103, 124]
[15, 23, 44, 90, 116]
[16, 4, 97, 106, 108]
[17, 19, 85, 111]
[18, 47, 60, 68, 74]
Is there a way to print it in this format?
0, 2, 20, 91, 114, 127
1, 6, 24, 114
I have tried
print>>f, "".join(list)
But it does not work, as it is a list of numpy64 floats.

You want to make strings out of each member of the list first. Try
print >>f, ', '.join(map(str,list))
Also, don't name variables list!

Try
",".join(str(i) for i in list))

hacky fix:
print(str(list).replace(']','').replace('[',''))

Converting them to strings should work
print >>f, ', '.join(str(elem) for elem in my_list)
and as Brien said, don't call your list list

If list is a numpy array of floats:
list.astype('str')
OR-You can also use csv to write np.arrays quickly:
import csv
import numpy as np
a = np.random.uniform(0,10,size = (5,5))
writer = csv.writer(open('txtfile.txt','wb'))
writer.writerows(a)
Yields txt file:
3.55183065126,1.05649949199,5.15510365109,1.0369928554,7.66646909667
9.5145737219,1.53877245296,5.53917128683,1.55343228883,8.78227048275
5.80408228776,2.58788175555,0.502704494319,1.63833152952,3.59898531148
2.94430872526,2.42069917781,5.75920106752,2.42453222446,1.73308148034
1.9579612159,0.609573767011,3.87717828624,7.86853109668,7.41038950637
or if you wanted integers, adding:
writer.writerows(a.astype(int))
would yield
2,0,3,4,1
9,5,4,4,3
9,7,6,4,2
3,5,7,2,0
6,0,2,7,7

Firstly, you should use the with statement when dealing with files to ensure they are automatically closed even if the program encounters an error befor they finish. Secondly, you can replace for i in range(len(my_list)) and my_list[i] with for i in my_list and i. Also, having a variable called list overwrites the inbuilt type list. Common practice is to use a trailing underscore to avoid this.
This code should work (although I don't currently have Numpy installed to test it with)
with open("myfilename.txt","w") as f:
for i in my_particles:
list_ = []
list_.append(i.n)
for j in value.neighbours:
list_.append(j)
f.write(", ".join(str(n) for n in list_))
Note that this will erase the previous contents of the file. If you don't want this, open the file with "a" in the open function rather than "w".

Related

How can I create a random order list and including same numbers?

I want to create five random list but have same and not repeat number from 1-100.
I only know I can remove the number from a list which have all number I want and chose randomly put in to new list:
All_list is a list I save all the list I want to save random number from 1-100
number_list is the list including all number I want but it isn't random
number_list = list(range(1, 101))
for i in range(5):
All_list.append(list)
for a in range(1,101):
random_num = random.choice(number_list)
All_list[i-1].append(random_num)
number_list.remove(random_num)
But in:
All_list[i-1].append(random_num)
The above gives a typeError: descriptor 'append' for 'list' objects doesn't apply to a 'int' object. Why does this happen?
Can anyone help me rewrite this code? I will be appreciative about it.
The quick fix is, when calling All_list.append, to pass an empty list ([]), instead of the class list.
The error message is hard to understand without knowing some details about how methods work. Since All_list contains the class list, the following statement:
All_list[i-1].append(random_num)
is equivalent to:
list.append(random_num)
This grabs the append function from the list class and calls it in a way that treats random_num as the object instead of a list. Python sees that random_num is not an instance of the class where append is defined, so it throws an error.
Of course, you still have another error caused by the inner loop using up all of number_list. I don't know exactly what you're trying to do there.
Create list of random number, and group the random number into chunk_size size sublist.
import random
data = random.sample(range(1,101), 100)
chunk_size=int(len(data)/5)
_chunks=list(data [i:i+chunk_size]
for i in range(0, len(data ), chunk_size))
Output
[[98, 91, 87, 92, 85, 45, 3, 1, 76, 13, 11, 14, 43, 21, 42, 73, 26, 61, 63, 79], [12, 29, 2, 48, 10, 70, 30, 81, 44, 83, 49, 20, 24, 54, 77, 23, 40, 66, 32, 51], [31, 55, 9, 8, 60, 72, 19, 38, 57, 27, 68, 53, 41, 56, 35, 75, 17, 7, 64, 90], [33, 52, 71, 39, 62, 94, 16, 93, 37, 4, 99, 34, 65, 36, 58, 6, 82, 97, 88, 5], [86, 84, 78, 50, 18, 89, 59, 46, 100, 15, 47, 95, 74, 22, 67, 25, 69, 28, 80, 96]]
Your code on line 3 is where the problem is, All_list.append(list). I guess you meant to append number_list in All_list.
Hi #Peggy Lin and Welcome to Stack Overflow.
The error which you mentioned is due to the append function being used with an element of the list which is an integer unless you meant All_list to be a nested list.
Note:
You Should provide a minimal-reproducible-example along with a clear statement regarding what exactly is the problem with your code and also a clear sample output which you intend to get from the corrected code. Refer this to better your question
Please clarify the following points in your problem statement to get better and useful answers:
What type of a list do you require? A nested list containing 5 lists with their random numbers as their elements OR 5 seperate lists with each having random elements as their elements?
but have same and not repeat number from 1-100
Clarify what you meant by this.
I only know I can remove the number from a list which have all number I want and chose randomly put in to new list
This seems to indicate that either you already have a list OR You want to generate the list then modify it. Clarify the statement.
What purpose does number_list serve? What elements do you need in it?
Hope these will guide you in improving your question!

Python Bubble Sort Working, but incorrectly?

I am fairly new to python, and was trying to make my own bubble sort recursively. While error testing, i changed the code to this:
from sys import setrecursionlimit
setrecursionlimit(10000)
def bubbleSort(arr):
for index in range (len(arr)-1):
if arr[index] > arr[index+1]:
arr[index], arr[index+1] = arr[index+1], arr[index]
return bubbleSort(arr)
array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
array.reverse()
print(array)
sorted_array = bubbleSort(array)
print(array)
This initially prints a list from 99-0, and then after sorting, reverses the list, as is the idea of this algorithm. I just have no idea why this still works despite the fact that I assigned the sorted list to a new variable, printed the old variable, and it still prints a sorted list. In addition to this, I don't understand why the function doesn't return NoneType having finished sorting. Basically, my algorithm works, but I have no idea why. Can anyone help?
Just to help you understand how list works in Python.
Python call by reference or call by value
Python utilizes a system, which is known as “Call by Object Reference” or “Call by assignment”. In the event that you pass arguments like whole numbers, strings or tuples to a function, the passing is like call-by-value because you can not change the value of the immutable objects being passed to the function. Whereas passing mutable objects can be considered as call by reference because when their values are changed inside the function, then it will also be reflected outside the function.
Example 1:
# Python code to demonstrate
# call by value
string = "Geeks"
def test(string):
string = "GeeksforGeeks"
print("Inside Function:", string)
# Driver's code
test(string)
print("Outside Function:", string)
output-1
Inside Function: GeeksforGeeks
Outside Function: Geeks
Example 2
# Python code to demonstrate
# call by reference
def add_more(list):
list.append(50)
print("Inside Function", list)
# Driver's code
mylist = [10,20,30,40]
add_more(mylist)
print("Outside Function:", mylist)
Output-2
Inside Function [10, 20, 30, 40, 50]
Outside Function: [10, 20, 30, 40, 50]

Removing patterns in list

I have a list as following:
list=[80,"error",100,74,72,71,"error",39,38,63,"error",82,"error",62,75,23,77,87,"error",36]
and I want to remove "error" from the list :
llist=len(list)
for i in range(llist):
if list[i]=="error":
del list[i]
llist-=1
print(list)
but the compiler still display,"if list[i]=="error":
IndexError: list index out of range".
Where am I wrong?
Thanks in advance!
First don't use keyword list as variable name. Then conditional list comprehension is an easy way to do it:
my_list = [i for i in my_list if i != "error"]
Your problem here is that you are modifying the list length while trying to iterate over it. Perfect recipe for errors...
Your fix:
llist=len(list_)
for i in range(llist):
try:
if list_[i]=="error":
del list_[i]
llist-=1
except IndexError:
pass
print(list_)
OUTPUT:
[80, 100, 74, 72, 71, 39, 38, 63, 82, 62, 75, 23, 77, 87, 36]
Suggested:
Looks like you only need the numbers from the list:
import numbers
print([x for x in list_ if isinstance(x, numbers.Number)])
OUTPUT:
[80, 100, 74, 72, 71, 39, 38, 63, 82, 62, 75, 23, 77, 87, 36]
OR:
print([num for num in list_ if isinstance(num, (int,float))])
Try using remove function.
l = ['a', 'b', 'error', 'c']
l.remove('error')
Try this :
list1 = [i for i in list1 if i != 'error']
Try :
>>> list1=[80,"error",100,74,72,71,"error",39,38,63,"error",82,"error",62,75,23,77,87,"error",36]
>>> filter(lambda a: a != "error", list1)
[80, 100, 74, 72, 71, 39, 38, 63, 82, 62, 75, 23, 77, 87, 36]
In the last line, you're using "print(list)" but list is not your variable, even list can't be a variable.
You're changing the list after remove a element, dont do it. With the remove element is ready

Dealing with list of lists

I have a list with around 60000 characters.
The package I'm using takes only lists above 999 characters...
So for this example I have to run the function 60000/999 = 61 times.
Here is how a list looks like as an example:
liste=[ 'item1', 'item2', 'item3', 'item4'...]
Here is the issue, this number of characters will not be the same over time it can be less or more, so I have to take the length of the list into account.
Here is the code I'll use:
ids = function(liste)
for id in ids:
print(id)
I guess an idea should be to do a list of lists, the first big one including the 61 lists of 999 characters for each one and then do a loop:
for lists in list:
ids = function(lists)
for id in ids:
print(id)
Does someone have a better idea and/or knows how to create a list of lists depending on the length of the first big list?
It sounds like you want to process a long list in shorter chunks. You don't need to pre-process the list into a list of short lists. Here's a generator to break a list into sublists. Adapt as needed:
# Quick way to create a long list of numbers.
# I used a size that isn't a multiple of the chunk size to show that it doesn't matter.
items = list(range(105))
# Function to return smaller lists of the larger list.
def chunk(items,n):
for i in range(0,len(items),n):
yield items[i:i+n]
# Break the larger list into length 10 lists.
for subitems in chunk(items,10):
print(subitems) # process as you want...
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
[20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
[30, 31, 32, 33, 34, 35, 36, 37, 38, 39]
[40, 41, 42, 43, 44, 45, 46, 47, 48, 49]
[50, 51, 52, 53, 54, 55, 56, 57, 58, 59]
[60, 61, 62, 63, 64, 65, 66, 67, 68, 69]
[70, 71, 72, 73, 74, 75, 76, 77, 78, 79]
[80, 81, 82, 83, 84, 85, 86, 87, 88, 89]
[90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
[100, 101, 102, 103, 104]
So your code would look something like:
for sublist in chunk(liste,999):
taxids = accession.taxid(sublist)
for tax in taxids:
print(tax)
You seem to be new to Python. While creating lists in python, you don't need to give a length for that list. Why make a list of lists when you can make a list of strings, and still use it as a list of string? So, you DON'T have to the length into account.
I am not very clear about the question you asked, so correct me if I'm wrong. Also, I'm assuming that accession is a user-made function (made by you), to add new elements to the list.
Following is the code for an already defined liste
# I am assuming the list 'liste' is already defined
taxids = []
for i in liste:
taxids.append(list(i))
print(taxids)
Following is the code for when you want take inputs directly
n = input("no. of inputs that are to be given(the no. of elements that you need in the list): ")
for i in range():
elem = input("Enter the string: ")
taxids.append(list(elem))
print(taxids)
Let me know if this help!

Map() in python gives output once only

I was playing with map() function in Python 3.6.3 when I came across this below situation ::
>>> a = [12, 23, 13, 14, 15, 36]
>>> b = [34, 45, 35, 32, 34, 34]
>>> c = [34, 67, 89, 98, 98, 78]
>>> map(lambda x,y,z:x+y+z, a,b,c )
<map object at 0x0000017DD976EC88>
>>> e=map(lambda x,y,z:x+y+z, a,b,c )
>>> list(e)
[80, 135, 137, 144, 147, 148]
>>> list(e)
[]
My question is that why I cannot get output when I used list(e) second time. It's showing empty list.
Can anyone help me with this?
Because In Python 3, map returns an iterator, which you can only iterate over once. If you iterate over an iterator a second time, it will raise StopIteration immediately, as though it were empty. Thats why you get empty list second time when you call it.
For more info see this question
I hope this helps you! :)

Categories