I'm trying to figure out why my list looks ugly when printed:
alfa = []
alfa.append([])
alfa.append([])
a = 0
a = float(a)
print("Input the points, one per line as x,y.\nStop by entering an empty line.")
while a == 0:
start = input()
if start == '':
a = a + 1
else:
alfa[0].append(start.split(",")[0:1])
alfa[1].append(start.split(",")[1:2])
print(alfa)
with input of:
2,3
12,56
1,2
a
I get this:
[[['2'], ['12'], ['1']], [['3'], ['56'], ['2']]]
While if i try this simple Program found online:
elements = []
elements.append([])
elements.append([])
elements[0].append(1)
elements[0].append(2)
elements[1].append(3)
elements[1].append(4)
print(elements[0][0])
print(elements)
I get this:
[[1, 2], [3, 4]]
Why is this result much tidier than mine?
Try:
alfa[0].append(int(start.split(",")[0]))
alfa[1].append(int(start.split(",")[1]))
>>>[[2, 12, 1], [3, 56, 2]]
You're getting the quote marks because input() is interpreting the input as a string. It doesn't know that you want what you've typed to be a number, so it has to handle it in a default way. You have to tell the code that the input should be interpreted as an int.
Secondly, you're slicing the arrays when you use [0:1] to get an array consisting of the entries from 0 to 0, which is the same as getting element 0 directly, except you get an array with one element rather than just the element you want. Essentially, you are inserting [2] rather than 2.
The data from your input is strings, as shown by the quotation marks. Cast your strings to integers after the input. If you want to have the [1, 2] formatting without the extra brackets then you need to place numbers in alfa[0] and alfa[1] etc..
alfa = []
alfa.append([])
alfa.append([])
a = 0
a = float(a)
print("Input the points, one per line as x,y.\nStop by entering an empty line.")
while a == 0:
start = input()
if start == '':
a = a + 1
else:
alfa[0].append(int(start.split(",")[0]))
alfa[1].append(int(start.split(",")[1]))
print(alfa)
Oh, I see #Andrew McDowell has beat me to this. Well here you go anyway...
Related
I would like to find keywords from a list, but return a zero if the word does not exist (in this case: part). In this example, collabor occurs 4 times and part 0 times.
My current output is
[['collabor', 4]]
But what I would like to have is
[['collabor', 4], ['part', 0]]
str1 = ["collabor", "part"]
x10 = []
for y in wordlist:
for string in str1:
if y.find(string) != -1:
x10.append(y)
from collections import Counter
x11 = Counter(x10)
your_list = [list(i) for i in x11.items()]
rowssorted = sorted(your_list, key=lambda x: x[0])
print(rowssorted)
Although you have not clearly written your problem and requirements,I think I understood the task.
I assume that you have a set of words that may or may not occur in a given list and you want to print the count of those words based on the occurrence in the given list.
Code:
constants=["part","collabor"]
wordlist = ["collabor", "collabor"]
d={}
for const in constants:
d[const]=0
for word in wordlist:
if word in d:
d[word]+=1
else:
d[word]=0
from collections import Counter
x11 = Counter(d)
your_list = [list(i) for i in x11.items()]
rowssorted = sorted(your_list, key=lambda x: x[0])
print(rowssorted)
output:
[['collabor', 2], ['part', 0]]
This approach gives the required output.
In python, to get the count of occurrence dictionary is popular.
Hope it helps!
I want list from the user input from different lines WITHOUT knowing the number of lines.
I tried something and don't know how to replace value of 'n' from below code to get input from different WITHOUT requesting number of line from user.
arr = [ int(input()) for i in range(n)]
use a while True loop and keep checking for a special character or string to break the loop.
myList = list()
while True:
inp = input('input > ')
if inp == '-1': # using -1 to break loop, you could put your choice
break
myList.append(inp)
Here is a solution that I found..
it take input as:
1
2
3
4
8
7
5
6
and output as:
[1, 2, 3, 4, 8, 7, 5, 6]
My code is here....
arr = []
while True:
try:
line = input()
except EOFError:
break
arr.append(line)
arr = list(map(int, arr))
print(arr)
In a programming problem, I receive inputs like this:
6
7
8
5
4
And I want to create a list like [6, 7, 8, 5, 4] in this case, that is, a list of the numbers in the input.
I tried reading directly from input but then I printed my list and found out it was [6], so it only read the first line.
lst = []
while True:
n = input()
if n != '':
lst.append(int(n))
else:
break
print(lst)
This gives me an EOF error.
Use try-except block
lst = []
while True:
try:
n = input()
lst.append(int(n))
except EOFError:
break
print(lst)
I am trying to create a program which creates a Fibonacci sequence up to the value of the sequence being 200. I have the basic set up down where I can compute the sequence but I wish to display it in a certain way and I have forgotten how to achieve this.
I wish to write the numbers to an array which I have defined as empty initially, compute the numbers and assign them to the array and print said array. In my code below the computation is ok but when printed to screen, the array shows the value 233 which is above 200 and not what I'm looking for. I wish to print all the values under 200 which I've stored in an array.
Is there a better way to initially define the array for what I want and what is the correct way to print the array at the end with all elements below 200?
Code follows:
#This program calculates the fibonacci sequence up to the value of 200
import numpy as np
x = np.empty(14, float) #Ideally creates an empty array to deposit the fibonacci numbers in
f = 0.0 #Dummy variable to be edited in the while loop
#Here the first two values of the sequence are defined alongside a counter starting at i = 1
x[0] = 0.0
x[1] = 1.0
i = 1
#While loop which computes the values and writes them to the array x
while f <= 200:
f = x[i]+x[i-1] #calculates the sequence element
i += 1 #Increases the iteration counter by 1 for each loop
x[i] = f #set the array element equal to the calculated sequence number
print(x)
For reference here is a quick terminal output, Ideally I wish to remove the last element:
[ 0. 1. 1. 2. 3. 5. 8. 13. 21. 34. 55. 89.
144. 233.]
There are a number of stylistic points here. Firstly, you should probably use integers, rather than floats. Secondly, you should simply append each number to a list, rather than pre-define an array of a particular size.
Here's an interactive session:
>>> a=[0,1]
>>> while True:
b=a[-1]+a[-2]
if b<=200:
a.append(b)
else:
break
>>> a
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]
Here is a way without using indices:
a = 0
x = [a]
b = 1
while b <= 200:
x.append(b)
a, b = b, a+b
print(x)
factor = int(input("Which table would you like: "))
timestable = ([0,0])
for count in range(1,13):
timestable.append([0,0])
result = factor * count
timestable[count][0] = count
timestable [count][1] = result
for row in timestable:
print(row)
This is a program that allows a user to enter in a times table and prints out 1 * the number to 12 * the number. But whenever I go to run the code, I get this error message:
timestable[count][0] = count
TypeError: 'int' object does not support item assignment
Does anyone know what I have to change in my code?
As noted in comments, the problem is that the line timestable = ([0,0]) initializes timestable as just [0, 0]. Thus, after your first append, timestable looks like this: [0, 0, [0, 0]] instead of [[0, 0], [0, 0]], and the value behind timestable[count] is not the newly appended [0,0] but just the second 0 from initialization.
Maybe you wanted to create a one-tuple holding a list, but then you'd have to use ([0,0],) (note the trailing comma), but this won't do you any good, either, as you can not append to tuples. Instead, you should initialize it as a nested list. Also, you can shorten the body of the loop by not first appending zeros and then overwriting those zeros, but appending the correct values directly.
timestable = [[0,0]]
for count in range(1, 13):
timestable.append([count, factor * count])
However, you do not need the separate initialization and loop at all; you an just create timestable in a single list comprehension (note that here, the range starts from 0):
timestable = [[count, factor * count] for count in range(0, 13)]