L = [[[1, 2, 3], [4, 5]], 6]
output:
[1,2,3,4,5,6]
答案 0 :(得分:0)
如果所有你要做的是打印(x
正确平衡):
x=[1,[9,[[[[[2]]]]]],[[[2],[12,[2]],[10]]
print('[' + ''.join(c for c in str(x) if not c in '[]') +']')
输出:
[1, 9, 2, 2, 12, 2, 10]
这是临时性的。首先flattening x
在许多方面是更自然的解决方案。
答案 1 :(得分:0)
使用递归函数:
def flatten(list):
if type(list)==list:
answer = []
for item in list:
answer += flatten(item)
return answer
else:
return list
print(flatten(x))
说明:
递归函数将逐步分解列表,对于每个子列表,它将在较小的子列表上调用自己。
答案 2 :(得分:0)
单行递归:
public class SoftDeleteQueryVisitor : DefaultExpressionVisitor
{
private readonly List<DbScanExpression> _scanExpressions = new List<DbScanExpression>();
public override DbExpression Visit(DbScanExpression expression)
{
var table = (EntityType)expression.Target.ElementType;
if (table.Properties.All(p => p.Name != InterceptorConstants.IsDeletedColumnName))
{
return base.Visit(expression);
}
if (_scanExpressions.Contains(expression))
{
return base.Visit(expression);
}
var binding = expression.Bind();
return binding.Filter(
binding.VariableType
.Variable(binding.VariableName)
.Property(InterceptorConstants.IsDeletedColumnName)
.NotEqual(DbExpression.FromBoolean(true)));
}
private bool HasField(DbScanExpression expression)
{
var table = (EntityType)expression.Target.ElementType;
return table.Properties.Any(p => p.Name == InterceptorConstants.IsDeletedColumnName);
}
private bool HasExpression(DbExpression predicate)
{
if (predicate is DbAndExpression andExpression)
{
return HasExpression(andExpression.Left) || HasExpression(andExpression.Right);
}
if (predicate is DbComparisonExpression comparisonExpression &&
(comparisonExpression.ExpressionKind == DbExpressionKind.NotEquals ||
comparisonExpression.ExpressionKind == DbExpressionKind.Equals))
{
if (comparisonExpression.Right is DbPropertyExpression rightPropertyExpression &&
rightPropertyExpression.Property.Name == InterceptorConstants.IsDeletedColumnName ||
comparisonExpression.Left is DbPropertyExpression leftPropertyExpression &&
leftPropertyExpression.Property.Name == InterceptorConstants.IsDeletedColumnName)
{
return true;
}
}
return false;
}
public override DbExpression Visit(DbFilterExpression expression)
{
if (expression.Input.Expression is DbScanExpression scanExpression)
{
if (HasField(scanExpression))
{
if (HasExpression(expression.Predicate))
{
_scanExpressions.Add(scanExpression);
}
}
}
return base.Visit(expression);
}
}
和测试:
def flat(l):
return [i for ll in l for i in (flat(ll) if type(ll) is list else [ll])]
答案 3 :(得分:0)
更“hacky”的解决方案可能包括使用正则表达式:
import re
L = [[[1, 2, 3], [4, 5]], 6]
new_s = list(map(int, re.findall('\d+', str(L))))
输出:
[1, 2, 3, 4, 5, 6]