Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

Walrus operator in list comprehensions [Python 3.8.0]

We're not mind-readers, how do you expect us to know what you tried if you don't tell us?

The walrus operator works for me:

    >>> [spam for c in "hello world" if (spam:=c.upper()) in 'AEIOU']
    ['E', 'O', 'O']

    >>> [(spam:=x**2, spam+1) for x in range(5)]
    [(0, 1), (1, 2), (4, 5), (9, 10), (16, 17)]


What did you try, and what happened?
Comment

Walrus operator in list comprehensions [Python 3.8.0]

from os import getcwd, listdir, rename
import re

[rename(f'{p}{n}', f"{p}{''.join([w[:3] if len(w) > 3 else w for w in re.split('[-_. ]', n)[:-1]])}.{n.split('.')[-1]}")
 for n in listdir(p := f"{getcwd()}{input('Folder: ')}")]

When I run this code, I'm getting:
  File "C:Users1Desktopsn.py", line 4
    [rename(f'{p}{n}',f"{p}{''.join([w[:3] if len(w)>3 else w for w in re.split('[-_. ]',n)[:-1]])}.{n.split('.')[-1]}") for n in listdir(p:=f"{getcwd()}{input('Folder: ')}")]
                                                                                                                                         ^
SyntaxError: assignment expression cannot be used in a comprehension iterable expression

Process finished with exit code 1
Comment

PREVIOUS NEXT
Code Example
Python :: python crear variables 
Python :: what is python virtual environment 
Python :: py if else if 
Python :: least square fit straight line python 
Python :: imshow show nan as black 
Python :: print hello in python 
Python :: como escribir letras griegas en python 
Python :: import cv2 illegal instruction (core dumped) 
Python :: pandas read csv read all columns except few columns 
Python :: where are spacy models stored 
Python :: /usr/local/lib/python3.7/dist-packages/pytube/captions.py in xml_caption_to_srt(self, xml_captions) 
Python :: python 3.7.8 download 
Python :: python unsigned to signed integer 
Python :: python loop list backwards 
Python :: wikipedia api python 
Python :: extract list from string python 
Python :: if else condition python 
Python :: shuffle function in python 
Python :: readline python 
Python :: true in python 
Python :: pyton for 
Python :: Tree: Inorder Traversal 
Python :: list len python 
Python :: print dataframe name python 
Python :: where python packages are installed 
Python :: get length from variable python 
Python :: show which columns in dataframe have NA 
Python :: df.rename(index=str, columns={"A": "a", "C": "c"}) what does index=str means 
Python :: new line 
Python :: python catching exceptions 
ADD CONTENT
Topic
Content
Source link
Name
9+2 =