我在list of list
中有python
,我想使用单个print语句仅打印主列表中每个列表中的最后2个项目。这是我的示例列表:[['Violet', 1, '219'], ['Yellow', 2, '235'],['Yellow', 1, '25']]
。我基本上想要打印以上样本数据的是:
Following are the rooms that are currently available - {Floor:1,Room Number: 219},{Floor:2,Room Number:235},{Floor:1,Room Number: 25}
这是我写的印刷声明:
print("Following are the rooms that are currently available - - "+ str((",".join(lst))))
当我执行此操作时,我收到错误为TypeError: sequence item 0: expected str instance, list found
我还在学习python,因此我无法找到一种方法来打印我在上面显示的所需输出中的列表并解决此错误。我怎么能这样做?
答案 0 :(得分:1)
您可以使用以下内容:
lst = [['Violet', 1, '219'], ['Yellow', 2, '235'],['Yellow', 1, '25']]
res = "Following are the rooms that are currently available - - "
for room in lst:
res += '{Floor:' + str(room[1]) + ', Room Number:' + str(room[2]) + '},'
print(res)
如果你想删除最后一个',':
print(res[:-1])
答案 1 :(得分:1)
inner_list_str = ["{Floor: %d,Room Number: %s}" % (floor, room_number)
for _, floor, room_number in outer_list]
print "Following are the rooms that are currently available - " + ','.join(inner_list_str)
答案 2 :(得分:0)
d = [['Violet', 1, '219'], ['Yellow', 2, '235'],['Yellow', 1, '25']]
for L in d:
print 'Floor ' + str(L[1])+ ', Room number ' + L[2]
您可以简单地遍历列表并使用它们的indeces访问值。
答案 3 :(得分:0)
您只需使用for
循环遍历列表列表,然后打印第二个和第三个元素:
rooms = [['Violet', 1, '219'], ['Yellow', 2, '235'],['Yellow', 1, '25']]
print("Following are the rooms that are currently available - ")
for room in rooms:
print("{Floor:"+str(room[1])+",Room Number: "+str(room[2])+"},")
<强>解释强>
当您遍历列表列表时,room
被设置为每个列表:
第一个循环: room = ['Violet', 1, '219']
第二次循环: room = ['Yellow', 2, '235']
第三循环: room = ['Yellow', 1, '25']
然后在循环内部代码打印出room[1]
,这是列表中的第二个元素:
[&#39; Violet&#39;, 1 ,&#39; 219&#39;]
然后是room[2]
,这是第三个:
[&#39; Violet&#39;,1,&#39; 219&#39; ]
在线试用: