I ran this code and for some reason am just getting blank output. Thought it was because it had looped through it already and I just missed it, and there isn't anything left to print but this happens even for a new file. Super new to Python so any help would be appreciated! Unrelated, is there a way to remove the >> lines in Visual Studio so I can see the output more clearly?
>>>buffet = ('rice','salad','beets','oranges','cake')
>>>
>>>print(buffet)
>>>
>>>#menu rewritten
>>>
>>>buffet = ('rice','salad','beets','ice cream','fudge')
>>>
>>>print("\nModified dimensions:")
>>>
>>>for buffetitem in buffet:
print(buffetitem)
My output:
>>> buffet = ('rice','salad','beets','oranges','cake')
>>>
>>> print(buffet)
('rice', 'salad', 'beets', 'oranges', 'cake')
>>> #menu rewritten
>>>
>>> buffet = ('rice','salad','beets','ice cream','fudge')
>>> print("\nModified dimensions:")
Modified dimensions:
>>>
>>> for buffetitem in buffet:
... print(buffetitem)
...
You should press enter until you see the >>> and then enter again. Then it should run.
Related
For simplicity, we have an array
>>> arr = [1,2,3]
>>> for i in range(len(arr)):
>>> print(f'{arr[i]=}')
we get
>>> arr[i]=1
>>> arr[i]=2
>>> arr[i]=3
Would it be possible to expand to output like this
>>> arr[i=0]=1
>>> arr[i=1]=2
>>> arr[i=2]=3
or
>>> arr[0]=1
>>> arr[1]=2
>>> arr[2]=3
The real practice is to debug the code and check the array with >1000 elements.
Neither print(f'{arr[{i=}]=}') nor print(f'{arr[{i}]=}') can work for me.
I get the idea, but isn't it much more readable to just do:
for i, x in enumerate(arr):
print(f'arr[{i}]={x}')
I'm learning Spark with PySpark and I'm trying different staff with the function reduce() to properly understand it, but I did something and obtained a result that makes no sense to me.
The previous examples I executed with reduce was basic things like:
>>> a = sc.parallelize(['a','b','c','d'])
>>> a.reduce(lambda x,y:x+y)
'abcd'
>>> a = sc.parallelize([1,2,3,4])
>>> a.reduce(lambda x,y:x+y)
10
>>> a = sc.parallelize(['azul','verde','azul','rojo','amarillo'])
>>> aV2 = a.map(lambda x:(x,1))
>>> aRes = aV2.reduceByKey(lambda x,y: x+y)
>>> aRes.collect()
[('rojo', 1), ('azul', 2), ('verde', 1), ('amarillo', 1)]
But I tried this:
>>> a = sc.parallelize(['a','b','c','d'])
>>> a.reduce(lambda x,y:x+x)
'aaaaaaaa'
And I was expecting 'aaaa' as a result but no 'aaaaaaaa'
I was looking for an answers reading reduce() docs but I think I'm missing something.
Thanks!
Your x in lambda function is keep changing and so the x of last expression in each step is
a
aa
aaaa
which gives the last result aaaaaaaa. The number of character should be doubled with your expression.
Python 2.7.10 Shell
>>> a = "\\xe4\\xbb\\xa5\\xe5\\x8f\\xa5\\xe3\\x81\\x82\\xe3\\x81\\xae"
>>> b = "\xe4\xbb\xa5\xe5\x8f\xa5\xe3\x81\x82\xe3\x81\xae"
>>> print a
\xe4\xbb\xa5\xe5\x8f\xa5\xe3\x81\x82\xe3\x81\xae
>>> print b
以句あの
>>>
Var a is exactly same as var b in our eyes, but they are different in bytes/bits level. Now I want the print-result of a is same as the print-result of b, any solutions?
In other word, how to transfer a to b ?
Thanks in advance :)
Thanks to #Bishakh Ghosh 's answer, help me a lot.
In the specific version of my Python:
>>> print a.decode('string-escape')
以句あの
>>> print a.decode('unicode_escape')
以å¥ãã
>>> b = a.decode('string-escape')
Thanks ~~~ ((●'◡'●)ノ♥
This should do the trick:
b = a.decode('string-escape')
Or if you want to print a directly:
print(a.decode('string-escape'))
How do I replace a python object everywhere with another object?
I have two classes, SimpleObject and FancyObject. I've created a SimpleObject, and have several references to it. Now I'd like to create a FancyObject, and make all those references point to the new object.
a = SimpleObject()
some_list.append(a)
b = FancyObject()
a = b is not what I want, it just changes what a points to. I read the following would work, but doesn't. I get an error "Attribute __dict__ is not writable":
a.__dict__ = b.__dict__
What I want is the equivalent of (pseudo-C):
*a = *b
I know this is hacky, but is there any way to accomplish this?
There's no way. It'd let you mutate immutable objects and cause all sorts of nastiness.
x = 1
y = (x,)
z = {x: 3}
magic_replace(x, [1])
# x is now a list!
# The contents of y have changed, and z now has an unhashable key.
x = 1 + 1
# Is x 2, or [1, 1], or something stranger?
You can put that object in global namespace of separate module and than monkey patch it when you need.
objstore.py:
replaceable = object()
sample.py:
import objstore
b = object()
def isB():
return objstore.replaceable is b
if __name__ == '__main__':
print isB()#False
objstore.replaceable = b
print isB()#True
P.S. Rely on monkey patching is a symptom of bad design
PyJack has a function replace_all_refs that replaces all references to an object in memory.
An example from the docs:
>>> item = (100, 'one hundred')
>>> data = {item: True, 'itemdata': item}
>>>
>>> class Foobar(object):
... the_item = item
...
>>> def outer(datum):
... def inner():
... return ("Here is the datum:", datum,)
...
... return inner
...
>>> inner = outer(item)
>>>
>>> print item
(100, 'one hundred')
>>> print data
{'itemdata': (100, 'one hundred'), (100, 'one hundred'): True}
>>> print Foobar.the_item
(100, 'one hundred')
>>> print inner()
('Here is the datum:', (100, 'one hundred'))
Calling replace_all_refs
>>> new = (101, 'one hundred and one')
>>> org_item = pyjack.replace_all_refs(item, new)
>>>
>>> print item
(101, 'one hundred and one')
>>> print data
{'itemdata': (101, 'one hundred and one'), (101, 'one hundred and one'): True}
>>> print Foobar.the_item
(101, 'one hundred and one')
>>> print inner()
('Here is the datum:', (101, 'one hundred and one'))
You have a number of options:
Design this in from the beginning, using the Facade pattern (i.e. every object in your main code is a proxy for something else), or a single mutable container (i.e. every variable holds a list; you can change the contents of the list through any such reference). Advantages are that it works with the execution machinery of the language, and is relatively easily discoverable from the affected code. Downside: more code.
Always refer to the same single variable. This is one implementation of the above. Clean, nothing fancy, clear in code. I would recommend this by far.
Use the debug, gc, and introspection features to hunt down every object meeting your criterion and alter the variables while running. The disadvantage is that the value of variables will change during code execution, without it being discoverable from the affected code. Even if the change is atomic (eliminating a class of errors), because this can change the type of a variable after the execution of code which determined the value was of a different type, introduces errors which cannot reasonably be anticipated in that code. For example
a = iter(b) # will blow up if not iterable
[x for x in b] # before change, was iterable, but between two lines, b was changed to an int.
More subtly, when discriminating between string and non-string sequences (because the defining feature of strings is that iterating them also yields strings, which are themselves iterable), when flattening a structure, code may be broken.
Another answer mentions pyjack which implements option 3. Although it may work, it has all of the problems mentioned. This is likely to be appropriate only in debugging and development.
Take advantage of mutable objects such as a list.
a = [SimpleObject()]
some_list.append(a)
b = FancyObject()
a[0] = b
Proof that this works:
class SimpleObject():
def Who(self):
print 'SimpleObject'
class FancyObject():
def Who(self):
print 'FancyObject'
>>> a = [SimpleObject()]
>>> a[0].Who()
SimpleObject
>>> some_list = []
>>> some_list.append(a)
>>> some_list[0][0].Who()
SimpleObject
>>> b = FancyObject()
>>> b.Who()
FancyObject
>>> a[0] = b
>>> some_list[0][0].Who()
FancyObject
I got my results from sqlite by python, it's like this kind of tuples: (u'PR:000017512',)
However, I wanna print it as 'PR:000017512'. At first, I tried to select the first one in tuple by using index [0]. But the print out results is still u'PR:000017512'. Then I used str() to convert and nothing changed. How can I print this without u''?
You're confusing the string representation with its value. When you print a unicode string the u doesn't get printed:
>>> foo=u'abc'
>>> foo
u'abc'
>>> print foo
abc
Update:
Since you're dealing with a tuple, you don't get off this easy: You have to print the members of the tuple:
>>> foo=(u'abc',)
>>> print foo
(u'abc',)
>>> # If the tuple really only has one member, you can just subscript it:
>>> print foo[0]
abc
>>> # Join is a more realistic approach when dealing with iterables:
>>> print '\n'.join(foo)
abc
Don't see the problem:
>>> x = (u'PR:000017512',)
>>> print x
(u'PR:000017512',)
>>> print x[0]
PR:000017512
>>>
You the string is in unicode format, but it still means PR:000017512
Check out the docs on String literals
http://docs.python.org/2/reference/lexical_analysis.html#string-literals
In [22]: unicode('foo').encode('ascii','replace')
Out[22]: 'foo'