所以我目前正在尝试在 python 中做一些练习,我不太明白如何获取一个名为 s 的字符串列表并构建一个名为 r 的新子列表列表。
所以如果我有一个输入
s = [ 'It is', 'time', 'for', 'tea' ]
Run Code Online (Sandbox Code Playgroud)
输出列表 r 应包含:
[ [0,'It is'], [1,'time'], [2,'for'], [3,'tea'] ]
Run Code Online (Sandbox Code Playgroud)
有人可以帮助我理解并得到答案吗?
我试图这样做,但这不是我想要的答案。
def sub_lists(list1):
# store all the sublists
sublist = [[]]
# first loop
for i in range(len(list1) + 1):
# second loop
for j in range(i + 1, len(list1) + 1):
# slice the subarray
sub = list1[i:j]
sublist.append(sub)
return sublist
# driver code
s = [ 'It is', 'time', 'for', 'tea' ]
print(sub_lists(s))
Run Code Online (Sandbox Code Playgroud)
您可以enumerate为此使用:
s = [ 'It is', 'time', 'for', 'tea' ]
r = [[index, value] for index, value in enumerate(s)]
print(r)
Run Code Online (Sandbox Code Playgroud)
输出:
[[0, 'It is'], [1, 'time'], [2, 'for'], [3, 'tea']]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
47 次 |
| 最近记录: |