So, I have a python script which requires an input from the terminal. I have 20 different arrays and I want to print the array based on the input.
This is the code minus the different arrays.
homeTeam = raw_input()
awayTeam = raw_input()
a = (homeTeam[0])+(awayTeam[3])/2
b = (hometeam[1])+(awayTeam[2])/2
So, effectively what I want to happen is that homeTeam/awayTeam will take the data of the array that is typed.
Thanks
You may take input as the comma separated (or anything unique you like) string. And call split on that unique identifier to get list (In Python array and list are different).
Below is the example:
>>> my_string = raw_input()
a, b, c, d
>>> my_list = my_string.split(', ')
>>> my_list
['a', 'b', 'c', 'd']
Since you are having your list now, you already know what you need to do with it.
Alternatively, you may also extract list from raw_input by using eval. But it is highly recommended not to use eval. Read: Is using eval in Python a bad practice?
Below is the example:
>>> my_list = eval(raw_input())
[1, 2, 3, 4, 5]
>>> my_list[2]
3
Instead of 20 individual arrays you could use a dictionary.
d = {"team1": "someValue",
"team2": "anotherValue",
...
}
Then you can retrieve the values of a team by its name:
x = raw_input("team1")
d[x] will now return "someValue".
In your particular case, you can use arrays for the values of the dictionary, for example:
d = {"team1": [value1, value2, ...],
"team2": [...],
...
}
Now d[x] returns the array [value1, value2, ...].
Complete example
Finally, you could wrap all of this into a single function f:
def f():
homeTeam = d[raw_input("Enter home team: ")]
awayTeam = d[raw_input("Enter away team: ")]
a = (homeTeam[0] + awayTeam[3])/2
b = (homeTeam[1] + awayTeam[2])/2
return a, b
By calling f() the user will be prompted for two team names. And the function will return the values of both teams in form of a tuple.
You can take raw_input() as string and then you can use split function to make it array. While doing arithmetic stuff you need to do type casting. for example,
homeTeam = raw_input() ### 1,2,3,4
homeTeam = homeTeam.split(",")
awayTeam = raw_input() ### 5,6,7,8
awayTeam = awayTeam.split(",")
a = (int(homeTeam[0]) + int(awayTeam[3]))/2
b = (int(hometeam[1]) + int(awayTeam[2]))/2
Related
For example lets say I have a list as below,
list = ['list4','this1','my3','is2'] or [1,6,'one','six']
So now I want to change the index of each element to match the number or make sense as I see fit (needn't be number) like so, (basically change the index of the element to wherever I want)
list = ['this1','is2','my3','list4'] or ['one',1,'six',6]
how do I do this whether there be numbers or not ?
Please help, Thanks in advance.
If you don't wanna use regex and learn it's mini language use this simpler method:
list1 = ['list4','this1', 'he5re', 'my3','is2']
def mySort(string):
if any(char.isdigit() for char in string): #Check if theres a number in the string
return [float(char) for char in string if char.isdigit()][0] #Return list of numbers, and return the first one (we are expecting only one number in the string)
list1.sort(key = mySort)
print(list1)
Inspired by this answer: https://stackoverflow.com/a/4289557/11101156
For the first one, it is easy:
>>> lst = ['list4','this1','my3','is2']
>>> lst = sorted(lst, key=lambda x:int(x[-1]))
>>> lst
['this1', 'is2', 'my3', 'list4']
But this assumes each item is string, and the last character of each item is numeric. Also it works as long as the numeric parts in each item is single digit. Otherwise it breaks. For the second one, you need to define "how you see it fit", in order to sort it in a logic.
If there are multiple numeric characters:
>>> import re
>>> lst = ['lis22t4','th2is21','my3','is2']
>>> sorted(lst, key=lambda x:int(re.search(r'\d+$', x).group(0)))
['is2', 'my3', 'list4', 'this21']
# or,
>>> ['is2', 'my3', 'lis22t4', 'th2is21']
But you can always do:
>>> lst = [1,6,'one','six']
>>> lst = [lst[2], lst[0], lst[3], lst[1]]
>>> lst
['one', 1, 'six', 6]
Also, don't use python built-ins as variable names. list is a bad variable name.
If you just want to move element in position 'y' to position 'x' of a list, you can try this one-liner, using pop and insert:
lst.insert(x, lst.pop(y))
If you know the order how you want to change indexes you can write simple code:
old_list= ['list4','this1','my3','is2']
order = [1, 3, 2, 0]
new_list = [old_list[idx] for idx in order]
If you can write your logic as a function, you can use sorted() and pass your function name as a key:
old_list= ['list4','this1','my3','is2']
def extract_number(string):
digits = ''.join([c for c in string if c.isdigit()])
return int(digits)
new_list = sorted(old_list, key = extract_number)
This case list is sorted by number, which is constructed by combining digits found in a string.
a = [1,2,3,4]
def rep(s, l, ab):
id = l.index(s)
q = s
del(l[id])
l.insert(ab, q)
return l
l = rep(a[0], a, 2)
print(l)
Hope you like this
Its much simpler
I'm wondering if this is possible in python.
I'm accessing a list in this way:
print list[0]['name']
This is fine. Is there a way to use a variable?
I mean:
a="[0]['name']"
print list[a]
Thanks for your suggestions.
Some details:
I have a situation where I have something like this:
a = [{"name":"someone", "age":23}]
print a[0]['name']
But since I need to pass "[0]['name']" as parameter, I'd like to understand if this is possible.
Thanks,
cips
This is a simple matter of extracting the indices/keys from the string "[0]['name']" and then using those keys to index the list/dict structure.
data = [{"name":"someone", "age":23}]
keys = "[0]['name']"
# split the string into a list of indices/keys
keys = keys[1:-1].split('][')
# keys = ['0', "'name'"]
# the keys are all strings, so we have to convert
# each individual key to the correct type
import ast
keys = [ast.literal_eval(key) for key in keys]
# keys = [0, 'name']
# now use the list of indices/keys we generated to get the value
value = data
for key in keys:
value = value[key]
print(value) # output: someone
I hope not to be out of context, but maybe you can use a function like this if you can
convert s = "[0]['name']" to s = (0, 'name'):
def search_index(obj, itero):
try:
return search_index(obj[next(itero)], itero)
except StopIteration:
return obj
a = [{"name":"someone", "age":23}]
s = (0, 'name')
result = search_index(a, iter(s))
# >>> result = 'someone'
If you want to convert "[0]['name']" to (0, 'name') you can try this:
import re
reg = re.findall(r'\[(\d*?)\]|\[\'(\w*?)\'\]', "[0]['name']")
s = [int(index[0]) if not index[1] else index[1] for index in reg]
# [0, 'name']
It will convert the indexes to the right type, to work with either list or dicts.
In general it is dangerous to use eval but you essentially need to convert your string to perform your indexing.
So first you can get your list as a str using repr
>>> l = [{'name': 'bob'}]
>>> repr(l)
"[{'name': 'bob'}]"
then if you concatenate that with your index operation
>>> a = "[0]['name']"
>>> repr(l) + a
"[{'name': 'bob'}][0]['name']"
then eval the whole thing, it should do the trick
>>> eval(repr(l) + a)
'bob'
you can use the function eval('a[0][name]'), it will evaluate the string inside as a python code.
here is the reference:
https://docs.python.org/3/library/functions.html#eval
You can use exec command
exec("print(list{})".format(a))
I hope it works
I want to iterate over a certain range and create several sets that contain only the current i. (In the code I don't want to do this for every i, but it's about the general principle).
for i in range(5):
s=set(i)
print(s)
It says int object is not iterable. Why doesn't this work? Please keep the answers simple, I'm a newbie.
set() takes a sequence of values to add, and a single integer is not a sequence.
You could wrap it in a tuple or a list:
s = set((i,))
s = set([i])
but the better option is to use the {..} set literal notation:
s = {i}
The notation looks a lot like creating a dictionary, but you only list values, not keys.
Demo (on Python 2, where the representation uses set([..]) notation):
>>> i = 42
>>> set((i,))
set([42])
>>> set([i])
set([42])
>>> {i}
set([42])
Python 3 reflects sets using the literal notation:
>>> i = 42
>>> {i}
{42}
Set constructor set(x) requires x to be some container, like a list, or other set. You pass an integer, python tries to iterate over it, and fails.
In order to do so you need to pass a singleton of x, like that:
for i in range(5):
s = set([i]) # or s = set((i,))
print(s)
or through simplified set constructor
for i in range(5):
s = {i}
print(s)
or construct an empty set and add your element
for i in range(5):
s = set()
s.add(i)
print(s)
instead of using a for loop in range, you can also feed it to set (or a frozenset if you dont need to change it's content):
>>> set(range(5))
# {0, 1, 2, 3, 4}
I want a for loop in Python that can modify variables in the iterator, not just handle the value of the variables. As a trivial example, the following clearly does not do what I want because b is still a string at the end.
a = 3
b = "4"
for x in (a, b):
x = int(x)
print("b is %s" % type(b))
(Result is "b is a <class 'str'>")
What is a good design pattern for "make changes to each variable in a long list of variables"?
Short answer: you can't do that.
a = "3"
b = "4"
for x in (a, b):
x = int(x)
Variables in Python are only tags that references values. Theres is not such thing as "tags on tags". When you write x = int(x) if the above code, you only change what x points to. Not the pointed value.
What is a good design pattern for "make changes to each variable in a long list of variables"?
I'm not sure to really understand, but if you want to do things like that, maybe you should store your values not as individual variables, but as value in a dictionary, or as instance variables of an object.
my_vars = {'a': "3",
'b': "4" }
for x in my_vars:
my_vars[x] = int(my_vars[x])
print type(my_vars['b'])
Now if you're in the hackish mood:
As your variables are globals they are in fact stored as entries in a dictionary (accessible through the globals() function). So you could change them:
a = "3"
b = "4"
for x in ('a', 'b'):
globals()[x] = int(globals()[x])
print type(b)
But, as of myself, I wouldn't call that "good design pattern"...
As mentioned in another answer, there's no way to update a variable indirectly. The best you can do is assign it explicitly with unpacking:
>>> a = 3
>>> b = 4
>>> a, b = [int(x) for x in a, b]
>>> print "b is %s" % type(b)
b is <type 'int'>
If you have an actual list of variables (as opposed to a number of individual variables you want to modify), then a list comprehension will do what you want:
>>> my_values = [3, "4"]
>>> my_values = [int(value) for value in my_values]
>>> print(my_values)
[3, 4]
If you want to do more complicated processing, you can define a function and use that in the list comprehension:
>>> my_values = [3, "4"]
>>> def number_crunching(value):
... return float(value)**1.42
...
>>> my_values = [number_crunching(value) for value in my_values]
>>> print(my_values)
[4.758961394052794, 7.160200567423779]
This is an incredibly simple question (I'm new to Python).
I basically want a data structure like a PHP array -- i.e., I want to initialise it and then just add values into it.
As far as I can tell, this is not possible with Python, so I've got the maximum value I might want to use as an index, but I can't figure out how to create an empty list of a specified length.
Also, is a list the right data structure to use to model what feels like it should just be an array? I tried to use an array, but it seemed unhappy with storing strings.
Edit: Sorry, I didn't explain very clearly what I was looking for. When I add items into the list, I do not want to put them in in sequence, but rather I want to insert them into specified slots in the list.
I.e., I want to be able to do this:
list = []
for row in rows:
c = list_of_categories.index(row["id"])
print c
list[c] = row["name"]
Depending on how you are going to use the list, it may be that you actually want a dictionary. This will work:
d = {}
for row in rows:
c = list_of_categories.index(row["id"])
print c
d[c] = row["name"]
... or more compactly:
d = dict((list_of_categories.index(row['id']), row['name']) for row in rows)
print d
PHP arrays are much more like Python dicts than they are like Python lists. For example, they can have strings for keys.
And confusingly, Python has an array module, which is described as "efficient arrays of numeric values", which is definitely not what you want.
If the number of items you want is known in advance, and you want to access them using integer, 0-based, consecutive indices, you might try this:
n = 3
array = n * [None]
print array
array[2] = 11
array[1] = 47
array[0] = 42
print array
This prints:
[None, None, None]
[42, 47, 11]
Use the list constructor, and append your items, like this:
l = list ()
l.append ("foo")
l.append (3)
print (l)
gives me ['foo', 3], which should be what you want. See the documentation on list and the sequence type documentation.
EDIT Updated
For inserting, use insert, like this:
l = list ()
l.append ("foo")
l.append (3)
l.insert (1, "new")
print (l)
which prints ['foo', 'new', 3]
http://diveintopython3.ep.io/native-datatypes.html#lists
You don't need to create empty lists with a specified length. You just add to them and query about their current length if needed.
What you can't do without preparing to catch an exception is to use a non existent index. Which is probably what you are used to in PHP.
You can use this syntax to create a list with n elements:
lst = [0] * n
But be careful! The list will contain n copies of this object. If this object is mutable and you change one element, then all copies will be changed! In this case you should use:
lst = [some_object() for i in xrange(n)]
Then you can access these elements:
for i in xrange(n):
lst[i] += 1
A Python list is comparable to a vector in other languages. It is a resizable array, not a linked list.
Sounds like what you need might be a dictionary rather than an array if you want to insert into specified indices.
dict = {'a': 1, 'b': 2, 'c': 3}
dict['a']
1
I agree with ned that you probably need a dictionary for what you're trying to do. But here's a way to get a list of those lists of categories you can do this:
lst = [list_of_categories.index(row["id"]) for row in rows]
use a dictionary, because what you're really asking for is a structure you can access by arbitrary keys
list = {}
for row in rows:
c = list_of_categories.index(row["id"])
print c
list[c] = row["name"]
Then you can iterate through the known contents with:
for x in list.values():
print x
Or check if something exists in the "list":
if 3 in list:
print "it's there"
I'm not sure if I understood what you mean or want to do, but it seems that you want a list which
is dictonary-like where the index is the key. Even if I think, the usage of a dictonary would be a better
choice, here's my answer: Got a problem - make an object:
class MyList(UserList.UserList):
NO_ITEM = 'noitem'
def insertAt(self, item, index):
length = len(self)
if index < length:
self[index] = item
elif index == length:
self.append(item)
else:
for i in range(0, index-length):
self.append(self.NO_ITEM)
self.append(item)
Maybe some errors in the python syntax (didn't check), but in principle it should work.
Of course the else case works also for the elif, but I thought, it might be a little harder
to read this way.