将列表转换为格式化字符串 - 更新

问题描述 投票:-3回答:3

我一直在尝试编写一个python代码,它会自动从我的选择属性(drf)中给我一个列表

看起来像这样:

2011/2012
2012/2013
2013/2014
2014/2015
2015/2016
...

但我残酷地失败了。下面是我的代码(没有做任何合理的事情)

x = xrange(2011, 2015)
y = xrange(2012, 2016)
z = '%5d / %5d' % (x, y) 
print '\n'.join(z)

谢谢你的帮助。还有一件事所以我试着在我的drf模型中将我的输出属性放入我的选择属性中,它除了当我放置时它没有给我任何错误消息

Print z

它包括我运行时服务器控制台中的输出

Python manage.py runserver

这是我下面的代码,我想确定我做的是正确的

class studentship(models.Model):
      def datechoice():
             x = xrange(2011,2016)
             y = xrange(2012,2017)
             for tup in zip(x,y):
                    z = '%d/%d' %(tup[0], tup[1])

      pick_date = (datechoice())
      enroll = models.Charfield(max_Length = 1, choices = 
      pick_date, default = 'select school session')

谢谢你的帮助,我保证会急忙改进我的python。

python model django-rest-framework
3个回答
1
投票

您不能使用字符串格式来获取字符串列表。你必须显式写一个for循环:

x = xrange(2011, 2015)
y = xrange(2012, 2016)
z = ['%5d / %5d' % (a, b) for a,b in zip(x,y)] 
print '\n'.join(z)

0
投票

虽然,你的问题有点不清楚,试试这个:

for x in range(2011, 2016):
    print("{}/{}".format(x, x+1))

输出:

2011/2012
2012/2013
2013/2014
2014/2015
2015/2016

0
投票

将每个范围增加一年

x = xrange(2011, 2016) # 2016 is exclusive
y = xrange(2012, 2017)

# Use zip() to get tuples of years, one each from x and y
# print list(zip(x, y))
# [(2011, 2012), (2012, 2013), (2013, 2014), (2014, 2015), (2015, 2016)]

# Using zip(), loop through x and y
for tup in zip(x, y):
    z = '%d/%d' % (tup[0], tup[1])
    print z

2011/2012
2012/2013
2013/2014
2014/2015
2015/2016
>>>
© www.soinside.com 2019 - 2024. All rights reserved.