목록 항목을 인쇄하는 Pythonic 방법
이보다 Python 목록의 모든 개체를 인쇄하는 더 좋은 방법이 있는지 알고 싶습니다.
myList = [Person("Foo"), Person("Bar")]
print("\n".join(map(str, myList)))
Foo
Bar
이 방법은 정말 좋지 않습니다.
myList = [Person("Foo"), Person("Bar")]
for p in myList:
print(p)
다음과 같은 것이 없습니까?
print(p) for p in myList
그렇지 않다면 내 질문은 ... 왜? 포괄적 인 목록으로 이런 종류의 일을 할 수 있다면 목록 외부의 간단한 문장으로하는 것은 어떨까요?
Python 3.x를 사용한다고 가정합니다.
print(*myList, sep='\n')
from __future__ import print_function
mgilson이 주석에 언급 한대로를 사용하여 Python 2.x에서 동일한 동작을 얻을 수 있습니다 .
Python 2.x의 print 문을 사용하면 print(p) for p in myList
작동하지 않는 것에 대한 질문과 관련하여 일종의 반복이 필요 합니다. 동일한 작업을 수행하고 여전히 한 줄인 다음을 사용할 수 있습니다.
for p in myList: print p
을 사용하는 솔루션의 '\n'.join()
경우 목록 이해력과 생성기를 선호 map()
하므로 다음을 사용합니다.
print '\n'.join(str(p) for p in myList)
나는 이것을 항상 사용합니다.
#!/usr/bin/python
l = [1,2,3,7]
print "".join([str(x) for x in l])
[print(a) for a in list]
모든 항목을 인쇄하지만 끝에 None 유형을 제공합니다.
Python 2. *의 경우 :
Person 클래스에 대해 __str __ () 함수를 오버로드하면 map (str, ...)으로 부분을 생략 할 수 있습니다. 이를위한 또 다른 방법은 다음과 같이 함수를 만드는 것입니다.
def write_list(lst):
for item in lst:
print str(item)
...
write_list(MyList)
Python 3. * 에는 print () 함수에 대한 인수 sep 가 있습니다. 문서를 살펴보십시오.
@lucasg의 답변 확장 (받은 댓글에서 영감을 얻음) :
형식화 된 목록 출력 을 얻으려면 다음 행을 따라 수행 할 수 있습니다.
l = [1,2,5]
print ", ".join('%02d'%x for x in l)
01, 02, 05
이제는 ", "
구분 기호 (항목 사이에만, 끝이 아님) '02d'
를 %x
제공하고 와 결합 된 서식 지정 문자열은 각 항목에 대해 서식이 지정된 문자열을 제공합니다 x
.이 경우에는 두 자리 정수로 서식이 지정되고 왼쪽이 0으로 채워집니다.
각 콘텐츠를 표시하기 위해 다음을 사용합니다.
mylist = ['foo', 'bar']
indexval = 0
for i in range(len(mylist)):
print(mylist[indexval])
indexval += 1
함수에서 사용하는 예 :
def showAll(listname, startat):
indexval = startat
try:
for i in range(len(mylist)):
print(mylist[indexval])
indexval = indexval + 1
except IndexError:
print('That index value you gave is out of range.')
내가 도왔기를 바랍니다.
목록의 내용 만보고 싶다면 이것이 가장 편리하다고 생각합니다.
myList = ['foo', 'bar']
print('myList is %s' % str(myList))
간단하고 읽기 쉬우 며 형식 문자열과 함께 사용할 수 있습니다.
OP의 질문은 다음과 같은 것이 있습니까?
print(p) for p in myList # doesn't work, OP's intuition
대답은,이다 존재 입니다 :
[p for p in myList] #works perfectly
기본적으로 []
목록 이해를 위해 사용 하고 print
인쇄를 피하려면 제거하십시오 None
. 이유를 print
인쇄 None
볼 이
I recently made a password generator and although I'm VERY NEW to python, I whipped this up as a way to display all items in a list (with small edits to fit your needs...
x = 0
up = 0
passwordText = ""
password = []
userInput = int(input("Enter how many characters you want your password to be: "))
print("\n\n\n") # spacing
while x <= (userInput - 1): #loops as many times as the user inputs above
password.extend([choice(groups.characters)]) #adds random character from groups file that has all lower/uppercase letters and all numbers
x = x+1 #adds 1 to x w/o using x ++1 as I get many errors w/ that
passwordText = passwordText + password[up]
up = up+1 # same as x increase
print(passwordText)
Like I said, IM VERY NEW to Python and I'm sure this is way to clunky for a expert, but I'm just here for another example
Assuming you are fine with your list being printed [1,2,3], then an easy way in Python3 is:
mylist=[1,2,3,'lorem','ipsum','dolor','sit','amet']
print(f"There are {len(mylist):d} items in this lorem list: {str(mylist):s}")
Running this produces the following output:
There are 8 items in this lorem list: [1, 2, 3, 'lorem', 'ipsum', 'dolor', 'sit', 'amet']
참고URL : https://stackoverflow.com/questions/15769246/pythonic-way-to-print-list-items
'Programing' 카테고리의 다른 글
UI 테스트 실패-요소 나 하위 요소 모두 secureTextField에 키보드 포커스가 없습니다. (0) | 2020.08.14 |
---|---|
JavaScript를 사용하여 데이터 속성 설정 (0) | 2020.08.14 |
할당 전에 참조 된 로컬 (?) 변수 (0) | 2020.08.14 |
작업 복사본을 재설정하는 Subversion 명령이 있습니까? (0) | 2020.08.14 |
JUnit을 사용하여 환경 변수에 의존하는 코드를 테스트하는 방법은 무엇입니까? (0) | 2020.08.13 |