यह एक मजेदार सवाल था! चर लंबाई सूचियों के लिए इसे संभालने का एक और तरीका एक फ़ंक्शन का निर्माण करना है जो .formatविधि और सूची अनपैकिंग का पूरा लाभ लेता है । निम्नलिखित उदाहरण में मैं किसी भी फैंसी स्वरूपण का उपयोग नहीं करता हूं, लेकिन यह आसानी से आपकी आवश्यकताओं के अनुरूप बदला जा सकता है।
list_1 = [1,2,3,4,5,6]
list_2 = [1,2,3,4,5,6,7,8]
# Create a function that can apply formatting to lists of any length:
def ListToFormattedString(alist):
# Create a format spec for each item in the input `alist`.
# E.g., each item will be right-adjusted, field width=3.
format_list = ['{:>3}' for item in alist]
# Now join the format specs into a single string:
# E.g., '{:>3}, {:>3}, {:>3}' if the input list has 3 items.
s = ','.join(format_list)
# Now unpack the input list `alist` into the format string. Done!
return s.format(*alist)
# Example output:
>>>ListToFormattedString(list_1)
' 1, 2, 3, 4, 5, 6'
>>>ListToFormattedString(list_2)
' 1, 2, 3, 4, 5, 6, 7, 8'
(x)जैसा है वैसा ही हैx। एकल कोष्ठक में रखने का पायथन में कोई अर्थ नहीं है। आप आम तौर परfoo = (bar, )पढ़ने के लिए आसान बनाने के लिए कोष्ठक डालते हैं, लेकिनfoo = bar,ठीक यही काम करते हैं।