0

I have multiple sets of pairing lists stored in the dictionaries "dates" and "prices". The lists are of unkown sizes, but I would like to print them side by side as in:

date_value1 price_value1 date_value2 price_value 2  

At this moment, however I can only get it to print one after the other, as in:

for i in range(len(cities)):
    for j,k in zip(dates[i],prices[i]):
        print str(i) + " ; " +  j.text +" ; "+ k.text

I have tried to get it to do what I want by doing:

a = {}
for i in range(len(cities)):
    for j,k in zip(dates[i],prices[i]):
        print str(i) + " ; " +  j.text +" ; "+ k.text
        try:     a[i] = a[i-1] + " ; " + j.text +" ; "+ k.text
        except:  a[i] = " ; " + j.text +" ; "+ k.text

for i in a[len(cities)-1]:
    print a  

But it does something else entirely different which I really couldnt figure out.

Can you help? Thanks.


This is how I fixed my code. Thank you F.J

a = 100000
for i in xrange(len(citynames)):
    if len(precos[i]) < a: a = len(precos[i])
    print citynames[i], " ; "," ; ",
print    

for j in xrange(a):
    for i in xrange(len(citynames)):      
        print datas[i][j].text, " ; " ,precos[i][j].text, " ; ", 
    print
4

2 回答 2

2

所以我认为你在这里缺少的关键部分是如何在不自动添加换行符的情况下打印,只需,在末尾添加一个,例如:

for i in range(len(cities)):
    for j,k in zip(dates[i],prices[i]):
        print str(i) + " ; " +  j.text +" ; "+ k.text,
    print

print内部循环内的每个语句for都将附加一个空格而不是换行符。内部 for 循环之后的print语句只是打印换行符,因此在下一次迭代中您从新行开始(不确定是否需要)。

但是,更好的选择是研究使用str.join()来构造您要打印的整个字符串。例如:

for i in range(len(cities)):
    print ' '.join(str(i)+" ; "+j.text+" ; "+k.text for j, k in zip(dates[i], prices[i]))

请注意,我不知道这是否是您想要的确切格式,但您应该能够根据需要调整它。

于 2013-01-25T17:21:19.663 回答
1

另一个答案有效,但如果我在代码审查中看到这一点,我会将这个答案作为评论留下:

格式化数据,然后呈现。

创建一个行列表,以您想要的方式格式化。然后打印行。这种方法也更容易测试、更具可读性和解耦。

def append_to_rows(city, dates, prices, row):
  for date, price in zip(dates, prices):
    row.append(' ; '.join([city, date.text, price.text]))


def print_rows(rows):
  for row in rows:
    print row


def print_data(cities, prices, dates):
  rows = []
  for city in cities:
    append_to_rows(city, dates[city], prices[city], rows)
  print_rows(rows)

测试:

class Text(object):
  def __init__(self, text):
    self.text = text


cities = ['new york', 'san francisco', 'los angeles']
dates = {
  'new york': [
    Text('2008'),
    Text('2009'),
   ],
  'san francisco': [
    Text('2008'),
   ],
  'los angeles': [
    Text('2008'),
    Text('2009'),
    Text('2010'),
   ],
}
prices = {
  'new york': [
    Text('$500'),
    Text('$600'),
   ],
  'san francisco': [
    Text('$400'),
   ],
  'los angeles': [
    Text('$300'),
    Text('$400'),
    Text('$500'),
   ],
}

>>> print_data(cities, dates, prices)
new york ; 2008 ; $500
new york ; 2009 ; $600
san francisco ; 2008 ; $400
los angeles ; 2008 ; $300
los angeles ; 2009 ; $400
los angeles ; 2010 ; $500
于 2013-01-25T17:57:56.383 回答